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;
    };
  • 相关阅读:
    多线程的同步锁和死锁
    多线程同步
    oracle11g导出表时会发现少表,空表导不出解决方案
    GET和POST两种基本请求方法的区别
    数据库优化
    JavaScript中的基本数据类型
    Spring Data Jpa简单了解
    单例和多例详解
    jsp九大内置对象
    JavaEE 前后端分离以及优缺点
  • 原文地址:https://www.cnblogs.com/deerfig/p/6675605.html
Copyright © 2011-2022 走看看