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.java

For example,
Given nums = [0, 1, 3] return 2.spa

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

解答:
一開始個人思始很簡單,排序,查找:排序

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:it

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;
}
相關文章
相關標籤/搜索