My java solution o(n)


  • 0
    L
    public class Solution {
    public int missingNumber(int[] nums) {
        int sum = 0;
        for(int num : nums){
            sum += num;
        }
    
        return   (nums.length )*(nums.length+1) /2 - sum;
    }
    

    }


  • 0
    L
    you are so clever!But I have another answer:
    public class Solution {
        public int missingNumber(int[] nums) {
            Arrays.sort(nums);
            int  len= nums.length;
            if(len == 0){
                return 0;
            }
            if(len-1 == nums[len-1]){
                return len;
            }
            for(int i=0;i<nums.length;i++){
                if(i!=nums[i]){
                    return i;
                }
            }
            return len;
        }
    } 

Log in to reply
 

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