您的位置:首页 > 其它

Missing Number - LeetCode

2015-10-27 11:39 253 查看
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?

思路:我的方法是根据nums数组的大小,先计算出如果没有数缺少时所有数的和,利用公式 n * (n + 1) / 2即可。但这样会有溢出的危险。

看了discussion之后,被里面利用位运算的答案所深深震撼。

其主要思路就是,如果现在的数组里有一个数缺失,那么我们将这些数进行异或运算,然后再异或一遍完整的数。

那么没有缺失的数将会被异或两遍,而缺失的则只会被异或一遍。最后异或完的结果就是缺失的数字!

class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = 0;
for (int i = 0, n = nums.size(); i < n; i++)
res ^= nums[i] ^ (i + 1);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: