Missing number with one loop, no overflow


  • 4
    R

    class Solution {
    public:
    int missingNumber(vector<int>& nums) {

        int n = nums.size();
        
        int sum =0;
        
        for(int i=0; i<n; i++)
        {
            sum +=i; //for the summation from 0 to n;
            sum -=nums[i];
        }
        
        return sum+n;
    }
    

    };


  • 0
    V

    test scenarios: input [0], returns 1; [1], returns 0; [1,0], returns 2
    very nice solution but may fail some test scenarios. Mine was not as elegant but accepted (3 loops, O(n) runtime)


  • 0
    D

    It can NOT prevent overflow: for example nums[0] = INT_MAX-1;nums[1] = INT_MAX-2, ...


Log in to reply
 

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