首页 > 技术文章 > 442. Find All Duplicates in an Array

codeskiller 2017-02-15 14:51 原文

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]


本题做法与之前的Find All Numbers Disappeared in an Array比较类似,思路都是一样的几乎,代码如下:
 1 public class Solution {
 2     public List<Integer> findDuplicates(int[] nums) {
 3         List<Integer> res = new ArrayList<>();
 4         for(int i=0;i<nums.length;i++){
 5             int num = Math.abs(nums[i]);
 6             if(nums[num-1]<0){
 7                 res.add(num);
 8             }else{
 9                 nums[num-1] = -nums[num-1];
10             }
11             
12         }
13         return res;
14     }
15 }

 

 
 

推荐阅读