题目描述
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]
用负数保存是否访问过的标志,使得一个数组元素包含两个信息
Code
vector<int> findDuplicates(vector<int>& nums)
{
vector<int> ans;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] < 0)
{
if (nums[i] * -1 != i + 1)
{
if (nums[nums[i] * -1 - 1] < 0)
{
ans.push_back(nums[i] * -1);
continue;
}
int temp = nums[i] * -1;
nums[temp - 1] *= -1;
}
else
{
ans.push_back(nums[i] * -1);
continue;
}
}
else
{
if (nums[i] != i + 1)
{
if (nums[nums[i] - 1] < 0)
{
ans.push_back(nums[i]);
continue;
}
int temp = nums[i];
nums[temp - 1] *= -1;
}
else
{
nums[i] *= -1;
}
}
}
return ans;
}