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?
思路是用异或的思想,比如[0, 1, 2, 3, 5],那么用这种方法便是:
res = 6;res = 6^ 0^0 ^ 1^1 ^ 2^2 ^ 3^3 ^ 4^5 ^ 5^6,很容易看出来了。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res = nums.size();
int i=0;
for(auto e : nums) {
res ^= e;
res ^= i;
i++;
}
return res;
}
};
本文介绍了一种线性时间复杂度和常数额外空间复杂度的方法来找出包含0到n范围内n个不同整数的数组中缺失的那个数。通过使用异或操作,文章提供了一个简洁高效的C++实现方案。
157

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



