Loading

【leetcode】448. Find All Numbers Disappeared in an Array

  Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
  1、方法一,创建一个标记数组,用于记录数组中出现的数字。
//利用hashmap 进行标记
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        
        int hashmap[100001]={0};
        vector<int> res;
        //利用hash map来做 更简单 o(n)的复杂度
        for(auto nn:nums){
            hashmap[nn-1]=1;
        }
        for(int i=0;i<nums.size();++i){
            if(hashmap[i]==0){
                res.push_back(i+1);
            }
        }
        return res;
        
    }
};

  2、利用set排序去重特性,检索缺失的数字

//利用set 去重排序
class Solution {
public:
    vector<int> findDisappearedNumbers(vector<int>& nums) {
        
        //如果用find 函数的话 时间复杂度就是o(n^2)
        int len=nums.size();
        set<int>dp; //排序加去重
        vector<int>res;
        for(auto nn:nums){
            dp.insert(nn);
        }
        int k=1;
        for(auto dd:dp){
            if(k<dd){
                while(k<dd){
                    res.push_back(k);
                    k++;
                }
            }
            k++;
        }
        while(k<=len){
            res.push_back(k);
            k++;
        }
        return res;
    }
};

 

 
posted @ 2021-11-20 13:57  aalanwyr  阅读(28)  评论(0编辑  收藏  举报