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]
题目大概意思是找出数组中出现两次的数字
最直接想到的是排序或者用map,但明显复杂度不是O(n)
所以采用通过数组下标的方式,并因为1 ≤ a[i] ≤ n
条件所以也不需要创建新的数组空间。
对于走过的下标将其值变成负数,再走到的时候通过判断正负将其加入到list中,但对于出现2次以上的话此方法会加入多次。
public static List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums.length <= 1) return res;
for (int i = 0; i < nums.length; i++) {
int next = Math.abs(nums[i]) - 1;
if (nums[next] < 0) {
res.add(next+1);
}
else {
nums[next] = -nums[next];
}
}
return res;
}