- Missing Number
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?
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = nums.size();
int i=0;
for(int i = 0; i < nums.size(); i++){
result = result ^ nums[i] ^ i;
}
return result;
}
};
1、a^b:按位异或,不同为1.
(a|b:按位或,有1为1;a&b:按位与,有0为0)
(&&且,||或,是逻辑运算,返回bool)
2、异或常用于交换两个整数的值而不必用第三个参数
a = 9;
b = 11;
a=a^b; 1001^1011=0010
b=b^a=b^a^b=a; 1011^0010=1001=9
a=a^b=a^b^a=b; 0010^1001=1011=11