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;
    };
  • 相关阅读:
    四、运算符
    三、Golang 变量
    二、Golang的概述
    一、Golang开山篇
    部分技术使用
    Teleport_实战
    zabbix_浅谈
    渗透测试工具集合(漏洞练习平台)
    常见开源监控软件的介绍
    Ansible-大保健
  • 原文地址:https://www.cnblogs.com/deerfig/p/6675605.html
Copyright © 2011-2022 走看看