Description
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]
Thinking Process
- Walk through the array, for nums[i] mark the nums[abs(nums[i]) - 1] as its negative counterparts, this indicates that abs(nums[i]) is in the array. If we see the negative number twice, then the number represented by its index must have appeared more than once in the array.
Code
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
int n = nums.length;
List<Integer> res = new LinkedList<>();
for(int i = 0; i < n; i++){
if(nums[Math.abs(nums[i]) - 1] < 0){
res.add(Math.abs(nums[i]));
}else{
nums[Math.abs(nums[i]) - 1] = - Math.abs(nums[Math.abs(nums[i]) - 1]);
}
}
return res;
}
}
Complexity
- O(n) for time
- O(1) for space excluding the space needed for output