Shared two different solutions in C++


  • 0
    R

    Approach 1:

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

    Approach 2:

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int len=nums.size();
            if(len==0) return 0;
            if(len==1){
                if(nums[0]==0) return 1;
                else           return 0;
            }
            for(int i=0; i<len; ){
                if(nums[i]>=len || nums[i]==i) i++;
                else{
                    swap(nums[i], nums[nums[i]]);
                }            
            }
            int pre=-1;
            for(int i=0; i<len; ++i){
                if(nums[i]!=pre+1) return pre+1;
                else
                    pre=nums[i];
            }
            return nums[len-1]+1;
        }
    };

Log in to reply
 

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