class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = 0;
for(int i = 0; i < nums.size(); ++i){
result = result ^ i ^ nums[i];
}
return result ^ nums.size();
}
};
重点在于数组是从0开始的;
The basic idea is to use XOR operation. We all know that a^b^b =a, which means two xor operations with the same number will eliminate the number and reveal the original number.
In this solution, I apply XOR operation to both the index and value of the array. In a complete array with no missing numbers, the index and value should be perfectly corresponding( nums[index] = index), so in a missing array, what left finally is the missing number.
例如:
index:0, 1, 2, ..., k-1, k, ..., n-1
elements: 0, 1, 2, ..., k-1, k+1, ..., n
最后分别剩下了k和n,最后再与n异或,就只剩下k了。骚