C++ O(n) time and O(1) space.


  • 0
    U

    It's quite easy to compute a - b AND a^2 - b^2. From then on, find a and b becomes trivial.

    class Solution {
    public:
        vector<int> findErrorNums(vector<int>& nums) {
            int a_minus_b = 0;
            int aa_minus_bb = 0;
            for (int i = 0; i < nums.size(); i++) {
                a_minus_b += nums[i] - (i + 1);
                aa_minus_bb += nums[i] * nums[i] - (i + 1) * (i + 1);
            }
            int a_plus_b = aa_minus_bb / a_minus_b;
            int a = (a_plus_b + a_minus_b) / 2;
            int b = a_plus_b - a;
            return vector<int>({a, b});
        }
    };
    

Log in to reply
 

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