LeetCode OJ|Array|Find All Numbers Disappeared in an Array

LeetCode OJ|Array|Find All Numbers Disappeared in an Array

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]   

解析:这道题简单地考虑应该会用两个for循环,外面的for循环从1到n,内层循环将外面的数字与向量里面的元素以此比较,若没有出现,则将外面的数字添加到结果向量中去。但是注意到题目的要求是O(n)runtime,所以这种简单的方法需要的时间复杂度是O(n^2)。既然要缩减时间,那我们就考虑牺牲空间了。可以再多建一个向量,起到像图的遍历里面visit数组一样的功能。然后将原向量里面的元素映射到新向量的地址,这样就起到了记住向量元素的作用。

将向量b初始化为大小与原向量一样,元素全为0。然后再将原向量里面的元素对应的地址设为1,再通过一个for循环就可以找出那些原向量里面没有的元素了。

源代码如下:

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