美文网首页Leetcode
Leetcode 645. Set Mismatch

Leetcode 645. Set Mismatch

作者: SnailTyan | 来源:发表于2018-08-30 19:04 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Set Mismatch

    2. Solution

    • Version 1
    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            vector<int> result;
            int flag[nums.size() + 1] = {0};
            for(int index : nums) {
                flag[index]++;
            }
            int duplicate = 0;
            int missing = 0;
            for(int i = 1; i < nums.size() + 1; i++) {
                if(flag[i] == 2) {
                    duplicate = i;
                }
                if(flag[i] == 0) {
                    missing = i;
                }
            }
            result.push_back(duplicate);
            result.push_back(missing);
            return result;
        }
    };
    
    • Version 2
    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            vector<int> result;
            int duplicate = 0;
            int missing = 0;
            for(int i = 0; i < nums.size(); i++) {
                if(nums[abs(nums[i]) - 1] < 0) {
                    duplicate = abs(nums[i]);
                    continue;
                }
                nums[abs(nums[i]) - 1] = -nums[abs(nums[i]) - 1];
            }
            for(int i = 0; i < nums.size(); i++) {
                if(nums[i] > 0) {
                    missing = i + 1;
                }
            }
            result.push_back(duplicate);
            result.push_back(missing);
            return result;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/set-mismatch/description/

    相关文章

      网友评论

        本文标题:Leetcode 645. Set Mismatch

        本文链接:https://www.haomeiwen.com/subject/idvdwftx.html