题目:
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是数组的大小,而不是数组中的最大数。其次要注意代码的效率,如果每次循环都从数组的第一个数开始,会超时。思路是先把数组排序,循环每次不从第一个数开始,而是从上一个循环结束的位置开始,这样不会超时。判断条件是,数组里的数没有跟i相等的数,直接就是比i大的数,则把这个数放入vector。
class Solution {
public:
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> a;
sort(nums.begin(),nums.end());
int ma=nums.size();
int c=0;
for(int i=1;i<=ma;i++)
{
for(int k=c;k<nums.size();k++)
{
if(nums[k]==i)
break;
else if(nums[k]>i)
{
a.push_back(i);
break;
}
else if(k==nums.size()-1)
a.push_back(i);
c=k;
}
}
return a;
}
};