LeetCode 题解工作台

最小异或

给你两个正整数 num1 和 num2 ,找出满足下述条件的正整数 x : x 的置位数和 num2 相同,且 x XOR num1 的值 最小 注意 XOR 是按位异或运算。 返回整数 x 。题目保证,对于生成的测试用例, x 是 唯一确定 的。 整数的 置位数 是其二进制表示中 1 的数目。 示…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

根据题目描述,我们先求出 的置位数 ,然后从高位到低位枚举 的每一位,如果该位为 ,则将 的对应位设为 ,并将 减 ,直到 为 。如果此时 仍不为 ,则从低位开始将 的每一位为 的位置设为 ,并将 减 ,直到 为 。 时间复杂度 $O(\log n)$,其中 为 和 的最大值。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个正整数 num1num2 ,找出满足下述条件的正整数 x

  • x 的置位数和 num2 相同,且
  • x XOR num1 的值 最小

注意 XOR 是按位异或运算。

返回整数 x 。题目保证,对于生成的测试用例, x唯一确定 的。

整数的 置位数 是其二进制表示中 1 的数目。

 

示例 1:

输入:num1 = 3, num2 = 5
输出:3
解释:
num1 和 num2 的二进制表示分别是 0011 和 0101 。
整数 3 的置位数与 num2 相同,且 3 XOR 3 = 0 是最小的。

示例 2:

输入:num1 = 1, num2 = 12
输出:3
解释:
num1 和 num2 的二进制表示分别是 0001 和 1100 。
整数 3 的置位数与 num2 相同,且 3 XOR 1 = 2 是最小的。

 

提示:

  • 1 <= num1, num2 <= 109
lightbulb

解题思路

方法一:贪心 + 位运算

根据题目描述,我们先求出 nums2\textit{nums2} 的置位数 cnt\textit{cnt},然后从高位到低位枚举 num1\textit{num1} 的每一位,如果该位为 11,则将 xx 的对应位设为 11,并将 cnt\textit{cnt}11,直到 cnt\textit{cnt}00。如果此时 cnt\textit{cnt} 仍不为 00,则从低位开始将 num1\textit{num1} 的每一位为 00 的位置设为 11,并将 cnt\textit{cnt}11,直到 cnt\textit{cnt}00

时间复杂度 O(logn)O(\log n),其中 nnnum1\textit{num1}num2\textit{num2} 的最大值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def minimizeXor(self, num1: int, num2: int) -> int:
        cnt = num2.bit_count()
        x = 0
        for i in range(30, -1, -1):
            if num1 >> i & 1 and cnt:
                x |= 1 << i
                cnt -= 1
        for i in range(30):
            if num1 >> i & 1 ^ 1 and cnt:
                x |= 1 << i
                cnt -= 1
        return x
speed

复杂度分析

指标
时间O(\log{n})
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate's ability to apply greedy strategies to minimize XOR.

  • question_mark

    Check if they understand how to manipulate individual bits using bitwise operations.

  • question_mark

    Evaluate how clearly they explain the process of matching set bits and minimizing the XOR result.

warning

常见陷阱

外企场景
  • error

    Forgetting to match the number of set bits between x and num2.

  • error

    Incorrectly applying XOR operations or not fully understanding their properties.

  • error

    Failing to ensure that the solution works for all edge cases, including when num1 and num2 are very different.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow num1 and num2 to be larger or smaller, testing how the algorithm handles different ranges.

  • arrow_right_alt

    Introduce more complex constraints or multiple test cases to challenge optimization.

  • arrow_right_alt

    Modify the problem to find the maximum XOR value instead of the minimum.

help

常见问题

外企场景

最小异或题解:贪心·invariant | LeetCode #2429 中等