My c++ solution by one pass


  • 0
    X

    a simple solution to solve it by one pass.

    1. sort
    2. count sum of all number and easily get the duplicate when traversing
    3. compute missing number by (n + 1) * n / 2 - sum + duplicate
    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            int len = nums.size();
            int miss,dup,sum = 0;
            sort(nums.begin(),nums.end());
            for(int i = 0; i < len; i++)
            {
                sum += nums[i];
                if(i + 1 < len && nums[i] == nums[i + 1])
                {
                    dup = nums[i];
                }
            }
            miss = (len + 1) * len / 2 - sum + dup;
            return vector<int>{dup,miss};
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.