1

题目:
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?

解答:
一开始我的思始很简单,排序,查找:

public int missingNumber(int[] nums) {
    if (nums == null || nums.length == 0) return 0;
    int result = 0;
    
    Arrays.sort(nums);
    for (int i = 0; i < nums.length; i++) {
        if (result != nums[i]) {
            return result;
        }
        result++;
    }
    return nums.length;
}

但是可以用xor的triky方法,因为只有一个missing number,所以可以把其它所有的数都配好对,剩下这个就是我们要找的number:

public int missingNumber(int[] nums) {
    int xor = 0, i = 0;
    
    //这里很triky喔,因为只少了一个数,举个例子:
    //nums: 1, 3, 4
    //   i: 1, 2, 3, (4)
    //所以当我们把这些数xor的时候,唯一一个剩下的就是2, missing的这个数
    
    for (i = 0; i < nums.length; i++) {
        xor = xor ^ i ^ nums[i];
    }
    
    return xor ^ i;
}

guoluona
199 声望14 粉丝