/**
* As described in the problem,
* 1 ≤ a[i] ≤ n (n = size of array)
* therefore, we can use nums[nums[i]] = -nums[nums[i]] to help us which elements
* appear twice. Note that elements in the array appear at most twice.
*/
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
int index;
List<Integer> res = new ArrayList<Integer>();
for (int i=0; i<nums.length; i++) {
index = Math.abs(nums[i]);
if (nums[index-1] < 0) res.add(index);
else nums[index-1] = -nums[index-1];
}
return res;
}
}
Similar problem, Leetcode 448. Find All Numbers Disappeared in an Array