(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;
    }
};
相关推荐
froyoisle7 分钟前
CSP 真题解析:[CSP-J 2020-T3] 表达式
c++·算法·csp·信息学·信奥赛
geats人山人海11 分钟前
算法好题 2026.7.18
算法
文祐20 分钟前
C++类之虚函数表没有虚继承的菱形继承
开发语言·c++·算法
Lumos18629 分钟前
51单片机从零到实战(8)——串口通信
算法
小帽子_1231 小时前
大功率 PCS 双环闭环控制算法原理与实现
算法
buhuizhiyuci2 小时前
【算法篇】位运算 —— 基础篇
java·数据库·算法
Black蜡笔小新2 小时前
算法训练完了怎么上线?DLTM→AIS→EasyGBS三步交付流水线
人工智能·算法
sycmancia2 小时前
Qt——多线程与界面组件的通信
开发语言·qt·算法
想吃火锅10053 小时前
【leetcode】5.最长回文子串js
算法·leetcode·职场和发展
CoderYanger3 小时前
A.每日一题:1967题+1331题
java·程序人生·算法·leetcode·面试·职场和发展·学习方法