(leetcode算法题)面试题 17.19. 消失的两个数字

可以在O(n)的时间复杂度下得到这两个消失的数字的异或的结果,或者得到这两个数字的和

但是怎么从上面的结果中得到这两个数字?

比如对于异或的结果,可以知道这两个数字在哪一位的置位是不同的

然后再根据这一位把 [1, n] 分为两个不同的数字集合 A 和 B,

也把 nums 分为两种不同的数字集合 C 和 D

然后A ^ C得到 消失的数字①,B ^ D 得到消失的数字②

下面以[1, 14]中消失了两个数字为例

代码如下

cpp 复制代码
class Solution {
public:
    vector<int> missingTwo(vector<int>& nums) {
        int XORtotal = 0;
        for (auto& num : nums){
            XORtotal ^= num;
        }

        for (int i = 1; i <= nums.size() + 2; i++){
            XORtotal ^= i;
        }

        int judgeDigit = XORtotal & (-XORtotal);
        int XORtot1 = 0;
        int XORtot2 = 0;
        for (int i = 1; i <= nums.size() + 2; i++){
            if (judgeDigit & i){
                XORtot1 ^= i;
            }
            else{
                XORtot2 ^= i;
            }
        }

        for (auto& num : nums){
            if (judgeDigit & num){
                XORtot1 ^= num;
            }
            else{
                XORtot2 ^= num;
            }
        }
        vector<int> ret = { XORtot1, XORtot2 };
        return ret;
    }
};
相关推荐
阿崽meitoufa13 小时前
JVM虚拟机:垃圾收集算法
java·jvm·算法
练习时长一年13 小时前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
52Hz11813 小时前
力扣148.排序链表
leetcode
七号驿栈13 小时前
07_汽车信息安全算法在线验证工具(测试报告)
算法
啦哈拉哈13 小时前
【Python】知识点零碎学习4
python·学习·算法
iAkuya13 小时前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
爱喝可乐的老王13 小时前
线性回归模型案例:广告投放效果预测
算法·回归·线性回归
程序员-King.14 小时前
day151—双端队列—找树左下角的值(LeetCode-513)
算法·leetcode·二叉树·双端队列·队列
苦藤新鸡14 小时前
15 .数组右移动k个单位
算法·leetcode·动态规划·力扣
狐5714 小时前
2026-01-19-牛客每日一题-阅读理解
笔记·算法·牛客