zoukankan      html  css  js  c++  java
  • Leetcode: 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?
    
    Example:
    Input:
    [4,3,2,7,8,2,3,1]
    
    Output:
    [2,3]

    my solution: put integer A[i] at index A[i]-1 unless A[i] already equals i +1 or A[i] == A[A[i]-1]

    later scan again if at index i, A[i] != i+1, then A[i] is a duplicate

     1 public class Solution {
     2     public List<Integer> findDuplicates(int[] A) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         for (int i=0; i<A.length; i++) {
     5             if (A[i]!=i+1 && A[i]!=A[A[i]-1]) {
     6                 int temp = A[A[i]-1];
     7                 A[A[i]-1] = A[i];
     8                 A[i] = temp;
     9                 i--;
    10             }
    11         }
    12         for (int i=0; i<A.length; i++) {
    13             if (A[i] != i+1)
    14                 res.add(A[i]);
    15         }
    16         return res;
    17     }
    18 }

    Better solution: without destroying the input array

    when find a number i, flip the number at position i-1 to negative.

    if the number at position i-1 is already negative, i is the number that occurs twice.

     1 public class Solution {
     2     public List<Integer> findDuplicates(int[] nums) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         for (int i=0; i<nums.length; i++) {
     5             int index = Math.abs(nums[i])-1;
     6             if (nums[index] < 0) {
     7                 res.add(index+1); // index + 1 == Math.abs(nums[i])
     8             }
     9             else nums[index] = -nums[index];
    10             
    11         }
    12         return res;
    13     }
    14 }
  • 相关阅读:
    2015个人年度总结
    矢量图标的使用
    onsrcoll和scrollTop兼容与实现
    我们,曾是阿里宝宝
    linux 基本操作笔记
    认识与学习shell
    两道有趣的面试题
    使用css保持一定宽高比例
    我在 超级课程表 实习的那个月
    3、4月学习总结,如愿阿里前端实习生
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6169361.html
Copyright © 2011-2022 走看看