[leetcode]645. Set Mismatch

[leetcode]645. Set Mismatch


Analysis

准备尝试黑咖啡~—— [孩怕~]

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.
找到重复的元素和缺失的元素,输入数组是没有顺序的。

Implement

也是不懂为啥自己第一次会写出这么繁琐又低效的方法,还是要多练啊!

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> tmp(nums.begin(), nums.end());
        sort(tmp.begin(), tmp.end());
        int len = nums.size();
        int n = tmp[len-1];
        map<int, int> mymap;
        vector<int> res;
        for(auto num:nums){
            if(mymap.find(num) == mymap.end())
                mymap[num] = 1;
            else{
                mymap[num] = 2;
                res.push_back(num);
            }

        }
        bool flag = false;
        for(int i=1; i<=n; i++){
            if(mymap.find(i) == mymap.end()){
                res.push_back(i);
                flag = true;
            }
        }
        if(!flag)
            res.push_back(n+1);
        return res;
    }
};

第二种方法稍微……正常点….

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
       sort(nums.begin(), nums.end());
       int len = nums.size();
       int n = nums[len-1];
       bool has[n+1];
       for(int i=1; i<=n; i++)
           has[i] = false;
        int sum = (1+n)*n/2;
        vector<int> res;
        for(auto num:nums){
           if(!has[num]){
               has[num] = true;
               sum -= num;
           }    
            else
                res.push_back(num);
        }
        if(sum == 0)
            res.push_back(n+1);
        else
            res.push_back(sum);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81051475
今日推荐