LeetCode – Missing Number (Java)

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array. For example, given nums = [0, 1, 3] return 2.

Java Solution 1 – Math

public int missingNumber(int[] nums) {
    int sum=0;
    for(int i=0; i<nums.length; i++){
        sum+=nums[i];
    }
 
    int n=nums.length;
    return n*(n+1)/2-sum;
}

Java Solution 2 – Bit

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

Java Solution 3 – Binary Search

public int missingNumber(int[] nums) {
   Arrays.sort(nums);
   int l=0, r=nums.length;
   while(l<r){
       int m = (l+r)/2;
       if(nums[m]>m){
           r=m;
       }else{
           l=m+1;
       }
   }
 
   return r;
}

2 thoughts on “LeetCode – Missing Number (Java)”

  1. Java Solution 3 – Binary Search

    works only if numbers are in order!!!! which is not in description of task!!!!

    first two work always!!!!!!!

  2. public class Solution {
    public int missingNumber(int[] nums) {
    Arrays.sort(nums);
    if(nums[0] != 0)
    return 0;
    int i=1;
    for(i=1;i<nums.length;i++){
    if(nums[i] – nums[i-1] != 1)
    return i;
    }
    return i;
    }
    }

Leave a Comment