给定一个整型数组a,其中1 ≤ a[i] ≤ n (n为数组的长度), 有些项会出现两次,有些则只有一次。
找到该数组中所有出现过两次的项。
要求不用额外的空间还有时间复杂度为O(n)
英语原文:
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> result;
for (int i = 0; i < nums.size(); i++)
{
int n = nums[i];
if (nums[abs(n)-1] < 0)
result.push_back(abs(n));
else
{
nums[abs(n)-1] *= -1;
}
}
return result;
}
};