地址:https://leetcode.com/problems/find-all-duplicates-in-an-array/
题目:
Given an array of integers, 1 ≤ a[i] ≤ n n n ( n 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
)
O(n)
O(n) runtime?
Example:
Input: [4,3,2,7,8,2,3,1]
Output: [2,3]
理解:
数组本来是从1-n,现在某些元素重复了两侧,要找出重复的元素。
实现:
对于正常的数组,应该满足nums[i] == i + 1
,即1在0的位置。。。
对于某个元素,我们判断nums[i] != nums[nums[i] - 1]
是否成立。对于不存在重复的元素,要通过交换使得其在合适的位置上;对于重复的元素,只要其重复元素在本身的位置上就可以了。(也就是这步是把每个出现的元素的对应位置添上对应的元素),对于多余的,就随便放到当前的位置就可以了。
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
int i = 0;
while(i < nums.size()){
if(nums[i]!=nums[nums[i]-1]) swap(nums[i],nums[nums[i]-1]);
else i++;
}
for(i = 0;i<nums.size(); ++i){
if(nums[i]-1!=i)
res.push_back(nums[i]);
}
return res;
}
};