Easy Java Soln : Time O(n) and Space O(1)


  • 0
    P

    public class Solution {
    public int missingNumber(int[] nums) {

        boolean zero = false;
        int max=0;
        int sum=0;
        for(int i=0;i<nums.length;i++){
            
            if(nums[i]==0)
            zero=true;
            sum+=nums[i];
            if(nums[i]>max)max=nums[i];
        }
        int shouldBe = (max*(max+1))/2;
        if(shouldBe-sum!=0 )
             return shouldBe-sum;
         else if (zero){
             return max+1;
         }
         else{
             return 0;
         }
        
    }
    

    }


Log in to reply
 

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