Simple Java Solution, O(1) space and O(n) time


  • 2
    I
    public int missingNumber(int[] nums) {
        if(nums==null || nums.length == 0) return 0;
        
        int sum = 0;
        for(int i=0; i < nums.length; i++)
            sum = sum + nums[i];
        
        // Sum of n distinct numbers = n*(n+1)/2;
        int sumShouldBe = ((nums.length)*(nums.length+1))/2;
        
        return (sumShouldBe - sum);
    }

Log in to reply
 

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