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 }
  • 相关阅读:
    jQuery中常用方法和jQuery思维导图
    jQuery
    JS-AJAX and jQuery-AJAX
    Linux系统里导入maven项目
    maven项目里的ssh框架整合
    spring框架的两大核心:IOC和AOP
    JAVA的抽象类和接口
    JAVA面向对象的三大特征
    JAVA---面向对象
    JAVA---方法
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6169361.html
Copyright © 2011-2022 走看看