Find All Duplicates in an Array

时间:2023-01-21 12:43:31

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]
 public class Solution {
//使用index和负数来表示这个位置被访问过。 public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = ; i < nums.length; ++i) {
int index = Math.abs(nums[i]) - ;
if (nums[index] < ) {
res.add(Math.abs(index + ));
}
nums[index] = -nums[index];
}
return res;
}
}