题目
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 < a[i] <= n,(n为数组的大小),一些元素出现了一次,一次出现了两次。
在数组中找出出现了两次的元素。
要求:
不适用额外的空间,且时间复杂度为O(n)
思路
该题目和 448 - Find All Numbers Disappeared in an Array是相互对偶的题目。448 -Find All Numbers Disappeared in an Array是寻找没有出现的数,该题目是寻找出现了两次的数。
思路类似。
注:
1,首先从前往后遍历。
2,如果第i处的值,等于i。跳过处理下一个。
3,如果第i处的值,不等于i,则和nums[i]-1处的数据进行交换。如果交换的值和被交换的值相同,则说明找到一个出现两次的值。将该值存入结果,并将被交换处置为0。如果不相等,则交换。
代码
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int len = nums.size();
vector<int> res;
while(!isUp(nums)){
for(int i = 0;i < len; i++){
//如果元素值不等于索引值,则交换到元素应该在的位置上
if(nums[i]!= 0 && nums[i]-1 != i){
if(nums[nums[i] - 1] == nums[i] ){
res.push_back(nums[i]);
nums[i] = 0;
}else{
int tmp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = tmp;
}
}
}
}
return res;
}
bool isUp(vector<int> &nums){
for(int i = 0; i < nums.size(); i++){
if(nums[i] != 0 && nums[i] != i+1){
return false;
}
}
return true;
}
};