448. Find All Numbers Disappeared in an Array

来源:互联网 发布:淘宝卡dnf称号 编辑:程序博客网 时间:2024/04/30 15:27

题目

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]
Subscribe to see which companies asked this question.


思路

遍历,标记各个数的flag,再遍历flag数组求出缺失的数


代码

class Solution {public:    vector<int> findDisappearedNumbers(vector<int>& nums) {        size_t upBound = nums.size();        vector<int> result;        vector<bool> numFlag(upBound+1,false);        if(upBound == 0)        {            return result;        }        for(size_t i=0;i<upBound;i++)        {            numFlag[nums[i]] = true;        }        for(size_t i=1;i<=upBound;i++)        {            if(numFlag[i] == false)            {                result.push_back((int)i);            }        }        return result;    }};
0 0
原创粉丝点击