find all duplicates in an array

Find All Duplicates in an Array

Question

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:

1
2
3
4
5
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]

Analysis

从头遍历数组,数字num对应index的数字变为负数,假如遍历到某数num为负,代表该index出现过一次,将index+1添加到res中

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res=new ArrayList();
for(int i=0;i<nums.length;i++){
int index=Math.abs(nums[i])-1;
if(nums[index]<0)
res.add(index+1);
else
nums[index]=-nums[index];
}
return res;
}
}

Find All Numbers Disappeared in an Array

Question

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

1
2
3
4
5
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]

Analysis

同上,将出现过的num对应index的数字变为负的,第二次遍历的时候假如某数num为正,代表该index数字未出现过

Code

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