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;
}
};
本文介绍了一种利用异或操作解决寻找遗漏数字问题的方法。通过对比数组元素与0到n的完整序列,快速找到缺失的数字。
386

被折叠的 条评论
为什么被折叠?



