一、题目:
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
二、解题思路:
题中所给数字为1-n,而我们的数组下标刚好是0~n-1,据此,将所给数组中(每个值-1)作为数组下标,并且给数组a[每个值-1]赋值为复数,再遍历一遍数组,将(负的元素+1)入栈,返回。
顺便提一下,测试集中有一个空数组。使用if(nums.size()==0) return nums;
语句即可。
三、代码和结果:
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
int n = nums.size();
if(n==0) return nums;
int a[n];
for(int i=0;i<n;i++){
a[i]=1;
}
for (auto& num : nums) {
a[num - 1] = -1;
}
vector<int>ret;
for (int i = 0; i < n; i++) {
if (a[i] != -1) {
ret.push_back(i + 1);
}
}
return ret;
}
};
结果: