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]
给出一个数组,数组的元素是1~n范围内的数字,元素会出现1次或2次,找出出现2次的元素
思路:
因为不要有extra space而且是O(n) time。因此考虑在原数组上做,元素的范围在1~n,可以考虑把每个元素放到它对应的index的位置上,比如1就放在第1个,n放在最后一个。
遍历数组,调换位置,把元素放在应该在的位置。期间可能调换时会发现对应的index上已经是该元素,但这时不要把结果保存,因为可能重复,到全部调换完成之后,看对应位置上对不上的,就是结果。
比如[4,3,2,7,8,2,3,1]调换完后是[1, 2, 3, 4, 3, 2, 7, 8],找出nums[i] != (i+1)的保存到结果
注意:调换顺序时要先让nums[nums[i]-1] = nums[i]; 因为一旦nums[i]发生变化,后面nums[nums[i]-1]就不是正确的数字。
public List<Integer> findDuplicates(int[] nums) {
List<Integer> result = new ArrayList<>();
if(nums == null || nums.length <= 1) {
return result;
}
int n = nums.length;
for(int i = 0; i < n; i++) {
while(nums[i] != (i+1)) {
if(nums[i] == nums[nums[i]-1]) {
break;
}
int tmp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = tmp;
}
}
for(int i = 0; i < n; i ++) {
if(nums[i] != (i+1)) {
result.add(nums[i]);
}
}
return result;
}