448. Find All Numbers Disappeared in an Array

来源:互联网 发布:mysql 当前时间毫秒数 编辑:程序博客网 时间:2024/06/06 03:59

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.

这道题我采用的是设立一个数组,索引由提给vector中的数组成,然后设立一个检测数组flag,当vector中的数出现过一次,flag[这个数]=1,然后最后把flag=0的数put在一个新的vector里面。
代码如下:

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        int size=nums.size();        int flag[size+1];        vector<int>cnt;        for(int i=1;i<size+1;i++){            flag[i]=0;        }        for(int i=0;i<size;i++){            flag[nums[i]]=1;        }        for(int i=1;i<size+1;i++){            if(flag[i]==0)cnt.push_back(i);        }        return cnt;    }};
0 0