题目: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.
样例:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
因为题目中有要求,可以寻找一种时间复杂度只有n的算法。所以,我将所有可能出现的数字的波尔值设为0,如果出现,就将波尔值改变为1,最后全部查找一遍就能得出结果。
提交代码:
include
class Solution {
public:
vector findDisappearedNumbers(vector& nums) {
int len = nums.size();
bool ans[len + 1];
memset(ans, 0, sizeof(ans));
ans[0] = 1;
for(int i = 0; i < len; i++) {
if(!ans[nums[i]])
ans[nums[i]] = 1;
}
vector sna;
for(int i = 0; i <= len; i++)
if(!ans[i])
sna.push_back(i);
return sna;
}
};