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, 1, 2, 3, 5],那么用这种方法便是:
res = 6;res = 6^ 0^0 ^ 1^1 ^ 2^2 ^ 3^3 ^ 4^5 ^ 5^6,很容易看出来了。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = nums.size();
int i=0;
for(auto e : nums) {
res ^= e;
res ^= i;
i++;
}
return res;
}
};