题目:
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]
思路:
把数组元素当做下一个位置坐标,标记一下,如果再遇到就加入到返回数组中。
程序:
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
if(nums.size() <= 1)
return res;
for(int i = 0;i < nums.size();i++)
{
int next = abs(nums[i]) - 1;
if(nums[next] < 0)
res.push_back(next + 1);
else
nums[next] = -nums[next];
}
return res;
}
};