(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;
    }
};
相关推荐
Fanxt_Ja4 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下4 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶4 小时前
算法 --- 字符串
算法
博笙困了4 小时前
AcWing学习——差分
c++·算法
NAGNIP4 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP4 小时前
大模型微调框架之LLaMA Factory
算法
echoarts4 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客4 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法
徐小夕4 小时前
花了一天时间,开源了一套精美且支持复杂操作的表格编辑器tablejs
前端·算法·github
小刘鸭地下城4 小时前
深入浅出链表:从基础概念到核心操作全面解析
算法