Different Solution Using the Sum of the First n Natural Numbers


  • 0
    R

    We first find the sum of all of the numbers from 0 - nums.size() - 1. We then loop through our array subtracting each index nums[i] from this value and the value we are left with is the answer.

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int n = nums.size();
            n = n * (n + 1) / 2;
            
            for(int i = 0; i < nums.size(); i++) {
                n -= nums[i];
            }
            return n;
        }
    };
    

Log in to reply
 

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