3 Solutions, C++, All in 3-4 lines, constant space, linear time


  • 0
    H

    Solution -1 constant space linear time using x-or operation

     int missingNumber(vector<int>& nums) {
       int n=0;    
       for(auto x:nums) n=n ^ x;
       for(int i=0;i<nums.size()+1;i++) n=n^i;
       return n;
      }
    

    Solution -2 constant space linear time using summation

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

    Solution -2 linear space linear time

    int missingNumber(vector<int>& nums) {
     vector<int> n(nums.size()+1,0);
     for(auto x:nums) n[x]++;
     for(int i=0;i<nums.size()+1;i++) if(n[i]==0) return i;
    }

  • 0

    Wow, you managed to give n three different meanings, all different from the one in the problem specification :-P


Log in to reply
 

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