(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;
    }
};
相关推荐
凌冰_13 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi13 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜13 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄16 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
文丑颜不良啊20 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI20 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊21 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz38991 天前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子131 天前
【高级数据库】关系代数基本概念
算法
电科_银尘2 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法