Tinily improved C++ solution


  • 0
    T

    Keep track of duplicate in the first pass, and then you can break early in the second pass.

    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            int arr[nums.size()+1] = {0};
            vector<int> ret;
            for (int num : nums) {
                if (arr[num] == 1) {
                    ret.push_back(num);   // duplicate found
                } 
                ++arr[num];
            }
            for (int i = 1; i < nums.size() + 1; ++i) {
                if (arr[i] == 0) {
                    ret.push_back(i);  // missing found
                    break;  
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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