zoukankan      html  css  js  c++  java
  • 442.Find All Duplicates in an Array

    Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

    Find all the elements that appear twice in this array.

    Could you do it without extra space and in O(n) runtime?

    Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

    Find all the elements that appear twice in this array.

    Could you do it without extra space and in O(n) runtime?

    Example:

    Input:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [2,3]
    方法一:先进行排序,然后遍历看是否有重复的数
    var findDuplicates = function(nums) {
        var len = nums.length;
        var arr = [];
        nums.sort(function(a,b){
            return a-b;
        })
        for(var i = 0;i < len-1;){
            if(nums[i] == nums[i+1]){
                arr.push(nums[i]);
                i += 2;
            }else{
                i++;
            }
        }
        return arr;
    };

    方法二:对于每个nums[i],将其对应的nums[nums[i] - 1]取相反数,如果其已经是负数了,说明之前存在过,将其加入结果arr中即可

    var findDuplicates = function(nums) {
        var len = nums.length;
        
        var arr = [];
       
        for(var i = 0;i < len;i++){
           var temp = Math.abs(nums[i])-1;
           if(nums[temp] < 0){
               arr.push(temp+1);
           }
           nums[temp] = -nums[temp];
        }
        return arr;
    };
  • 相关阅读:
    复杂业务
    重析业务逻辑架构模式
    Katana介绍以及使用
    使用ServiceStack构建Web服务
    ASP.NET vNext 在 Mac OS
    用户端的防腐层作用及设计
    Mvc 模块化开发
    编程语言
    页面生命周期
    If you pay peanuts,you get monkeys
  • 原文地址:https://www.cnblogs.com/deerfig/p/6675605.html
Copyright © 2011-2022 走看看