LeetCode645(2021.7.4)

LC645. 错误的集合

class Solution {
public:
    vector<int> findErrorNums(vector<int>& nums) {
        vector<int> errorNums(2);
        int n = nums.size(), prev = 0;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < n; i++) {
            int curr = nums[i];
            if (curr == prev) errorNums[0] = prev;
            else if (curr - prev > 1) errorNums[1] = prev + 1;
            prev = curr;
        }
        if (nums[n - 1] != n) errorNums[1] = n;
        return errorNums;
    }
};

发表评论