Find All Duplicates in an Array
Given an array of integers, 1 ≤ a[i] ≤n(n= size of array), some elements appeartwiceand others appearonce.
Find all the elements that appeartwicein 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]
Solution:
If the number at position xxx is already negative, then the xxx must appeared twice.
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ret = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
int idx = Math.abs(nums[i]) - 1;
if(nums[idx] < 0) ret.add(idx+1);
nums[idx] = -nums[idx];
}
return ret;
}
}