4 lines C++ Solution N*(N+1) /2


  • 0
    T

    I tried the XOR method also but this one is simple and I think easier (maybe not better) to understand. Basically if you want to count every number from 1 to 100 you use the formula n * (n+1)/2. So What I did is sum the values in the vector and subtract that sum from the formula I stated based on nums.size().

        int missingNumber(vector<int>& nums) 
        {
            int sum = 0;
            for(auto i : nums)
                sum += i;
        return nums.size() * (nums.size() + 1) / 2 - sum;
        }
    

  • 0
    W

    This soulution work normally only when there is only one missing number in the array.
    Think about array: [1,3,5].


  • 0
    T

    Yes you are totally right. I was aware of that. Since the problem only stated one is missing I tried the above code and passed all cases. If more than one was indeed missing this option would not have worked.


Log in to reply
 

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