Simple C++ solution beats 97.78%


  • 0
    Z

    Since the array contain elements from 1 to n, we can first find the duplicate element a by using bitset, and we calculate the sum M of all elements during scanning the array. The sum N of 1 to n is already known so we can compute the missing element b = N-M+a.

    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            vector<int> res;
            bitset<10001> table; 
            int m = nums.size();
            int sum = (1+m)*m>>1;
            int act = 0;
            for(int i=0;i<m;i++){
                act+=nums[i];
                if(!table.test(nums[i])){
                    table.set(nums[i]);
                }
                else{
                    res.push_back(nums[i]);
                }
            }
            res.push_back(sum-act+res[0]);
            return res;
        }
    };
    

Log in to reply
 

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