Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
题目解析:给定一个数组,求解这个数组中丢失了哪个数字
思路:
- 1、 利用异或方法来求解这道题目,异或的性质是:两个相同的数异或结果为0,两个不同的数异或结果是1(二进制的表示方法),同时异或支持交换律和结合律,所以可以利用异或来求解只出现一次的数字。将数组中的元素与数组下标异或,两两消去,最后留下的就是丢失的数字。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len=nums.size(),res=0;
for(int i=0;i<len;i++)
{
res=res^i^nums[i];
}
return res^len;
}
};