题目:
给定一个数组,包含从 1 到 N 所有的整数,但其中缺了两个数字。你能在 O(N) 时间内只用 O(1) 的空间找到它们吗?
以任意顺序返回这两个数字均可。
示例 1:
输入: [1]
输出: [2,3]
示例 2:
输入: [2,3]
输出: [1,4]
提示:
nums.length <= 30000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/missing-two-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
1.通过额外和1~n+2异或,找到两个数字的异或结果 xor
2.因为两个数字不相等,那么至少存在一个bit不同,找到最低bit位
3.按照和最低bit位与的结果是一样的数值再做一次 nums 和 1~n+2的数值(排除了2个数字的其中一个)的异或,得到就是一个数字one
4.two=xor^one
代码:
class Solution {
public:
vector<int> missingTwo(vector<int>& nums) {
int n = nums.size();
int xorAll = 0;
for (int i = 0; i < n; ++i)
{
xorAll ^= nums[i];
}
for (int i = 1; i <= n + 2; ++i)
{
xorAll ^= i;
}
// 找到最低bit
int lastBit = xorAll & (-xorAll);
// 再做一次异或,但是需要满足lastBit
int one = xorAll;
for (int i = 0; i < n; ++i)
{
if (nums[i] & lastBit)
{
one ^= nums[i];
}
}
for (int i = 1; i <= n + 2; ++i)
{
if (i & lastBit)
{
one ^= i;
}
}
return {one, xorAll^one};
}
};