268. 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
.
268. 遗漏数字
给定一个数组,包含n个不一样的数字,0, 1, 2, ..., n
,找出其中漏掉的数字。
比如:给出 nums = [0, 1, 3]
返回 2
.
思路
使用异或操作,将数组与0-n
无缺失数据进行异或,得到的就是遗漏的数字。
代码
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size(), res=0;
for (int i=0; i<n; i++){
res ^= nums[i]^i;
}
return res^n;
}
};