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]
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int len = nums.size();
vector<int> res;
for(int i = 0; i < len; ++i)
{
if(nums[i] == i + 1)
continue;
else
{
while(nums[i] != i + 1 && nums[nums[i] - 1] != nums[i])
{
int tmp = nums[i];
nums[i] = nums[tmp - 1];
nums[tmp - 1] = tmp;
}
}
}
for(int i = 0; i < len; ++i)
{
if(nums[i] != i + 1)
res.push_back(nums[i]);
}
return res;
}
};
一遍遍的交换,直到所有的数字都在自己所在的位置,当出现不在自己位置的数字时,说明该数字是有重复的。