268. Missing Number

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.

Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

  • solution 1, n*(n+1)/2 - sum(array), overflow issue.
  • hash table.
  • bit manipulation.

think of the array as newArray = nums + [0...n], so each number show up twice except the missing one. similar to Single Number

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

results matching ""

    No results matching ""