Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
看到大小为N
的数组存放数字 1-N
, 就想到了静态链表。对于静态链表,存的元素就是next
的索引,如果这个元素没出现过,那么就没有人指向它。所以,如果把所有元素的next
都置为负数或者是0。之后再去找没被置零或者置负数的,就是了。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
for(int i = 0; i < nums.size(); ++i)
{
int val = abs(nums[i]) - 1;
if(nums[val] > 0)
nums[val] = -nums[val];
}
vector<int> res;
for(int i = 0; i < nums.size(); ++i)
if(nums[i] > 0)res.push_back(i+1);
return res;
}
};