[LeetCode]448. Find All Numbers Disappeared in an Array

水题

Posted by JinFei on February 4, 2020

题目描述

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.

Example1:

input : [4,3,2,7,8,2,3,1]

output : [5,6]

解题思路

  • 哈希思想
  • 遍历这个数组,如果出现,出现次数就累加
  • 然后遍历 1~n 这n个数,如果没出现,证明是缺失的值,放入res数组即可。
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        map<int, int> mmap;
        for(int i = 0; i < nums.size(); i++){
            mmap[nums[i]]++;
        }
        vector<int> res;
        for(int i = 1; i <= nums.size(); i++){
            if(mmap[i] == 0){
                res.push_back(i);
            }
        }
        return res;
    }
};