首页 > 学院 > 开发设计 > 正文

448. Find All Numbers Disappeared in an Array

2019-11-06 07:52:49
字体:
来源:转载
供稿:网友

题目

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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表