Monday, May 1, 2017

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:

There is one missing number between 0 and n. Let's say it's x.

If we want to find it, we can xor these number with 0, 1, ..., n to cancel out the duplicate pairs.

result = 0 ^ 0 ^ 1 ^ 1 ^ ... ^ x ^ (x + 1) ^ (x + 1) ^ ... ^ n ^ n = x, which is the missing number.

We use the index as 0 ~ n - 1, and nums.length as n.

The time complexity is O(n) and space complexity is O(1).



Code:


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