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]类似于448. Find All Numbers Disappeared in an Array,每次把nums[nums[i]]反转,如果碰到负数,说明这是第二次反转,也就是这个数是第二次出现。代码如下:
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i ++) {
int val = Math.abs(nums[i]) - 1;
if (nums[val] < 0)
res.add(val + 1);
nums[val] = -nums[val];
}
return res;
}
}