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

来源:互联网 发布:阿里云空间 编辑:程序博客网 时间:2024/05/16 09:35

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]
解析:求一个数组里面出现过两次的元素。要求时间复杂度为O(n),这道题倒没有太多的解释,和上一篇一样,建立一个新的向量,将元素的值和新向量的地址对应起来,就可以起到记忆元素的作用,然后用一个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;
        
    }
};

0 0