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?
一刷
類似于尋找哪個數字只出現了一次夏漱,其它的都出現兩次。
如果[0, 2, .., n-1]中間有一個數字miss, 數組長度n-1
那么每次與數組中的元素異或职员,與index異或麻蹋,最后留下的數字為miss
public class Solution {
public int missingNumber(int[] nums) {
int res = 0;
for(int i=0; i<nums.length; i++){
res ^= i^nums[i];
}
res ^= nums.length;
return res;
}
}