(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;
    }
};
相关推荐
Js.Tx34 分钟前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
秋天的怀念_David2 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
揽星河..3 小时前
【C语言】数组
c语言·开发语言·算法
careathers3 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法
听风若依3 小时前
C++模板初阶
c++·算法
纪念 2293 小时前
C++ 算法(模拟)
开发语言·c++·算法
揽星河..4 小时前
【C语言】函数
c语言·算法
zwc32104320554 小时前
Day 2:图像内存、数据类型与stride
c++·人工智能·opencv·算法·计算机视觉
重生之小比特4 小时前
【算法拾光】模拟|提莫攻击 + N 字形变换
算法·模拟
東隅已逝,桑榆非晚4 小时前
AVL数实现
c++·笔记·学习·算法