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.
思路:这道题和求数组中唯一的一个数类似,遍历对数组下标和值异或,最后剩下的就是缺失的数字
class Solution {
public:
//用异或来计算,非常方便!跟那个求数组中求只出现一次数字,其他都是两次的一个思路
int missingNumber(vector<int>& nums) {
int result = nums.size();
for(int i=0;i<nums.size();i++)
{
result ^= nums[i];
result ^= i;
}
return result;
}
};