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:
Input: [4,3,2,7,8,2,3,1] Output: [2,3]
Answer:
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
int[] aa = new int[nums.length+1]; //注意数组大小是n+1
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<nums.length;i++) {
if(aa[nums[i]]!=0) {
result.add(nums[i]);
} else {
aa[nums[i]] = 1;
}
}
return result;
}
}