Simple 4 lines Java

  • 0

    The idea is to add all the numbers from 1 to n-1 and subtract from it all the numbers in the array. The result should be the missing number.

    public int missingNumber(int[] nums) {
        int s = 0;
        for (int i=1; i<=nums.length; i++)
            s += i - nums[i-1];
        return ;

  • 0

    assumes nums is sorted
    wont work for {5,4,3,1}

  • 0

    I do not think {5,4,3,1} is a valid input

  • 0

    @vasuj: the problem statement said "n distinct numbers taken from 0, 1, 2, ..., n". Your array has 4 elements, so the max element should be 4, so 5 cannot be in there.

Log in to reply

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