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]
思路:把数放map里作为key,然后把value设置为1(重复设置也了还是1),然后从1到n找哪个数不在map里数,把它放在ans里。
好像可以直接用set去重,因为我觉得map的话可以不用从新排序了,题目应该要输出一个顺序的吧。
刚开始我先用sort排序在用的其他方法对比,然后sort复杂度超时。
map里的count(i)可以统计元素i是否出现,不出现返回0
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int>ans;
map<int, int> hash;
for(int i=0;i<nums.size();++i){
hash[nums[i]]=1;
}
for(int i=1;i<=nums.size();++i){
if(hash.count(i)!=1){
ans.push_back(i);
}
}
return ans;
}
};