当前位置:网站首页>421. 数组中两个数的最大异或值
421. 数组中两个数的最大异或值
2022-07-26 13:23:00 【Sun_Sky_Sea】
421. 数组中两个数的最大异或值
原始题目链接:https://leetcode.cn/problems/maximum-xor-of-two-numbers-in-an-array/
给你一个整数数组 nums ,返回 nums[i] XOR nums[j] 的最大运算结果,其中 0 ≤ i ≤ j < n 。
进阶:你可以在 O(n) 的时间解决这个问题吗?
示例 1:
输入:nums = [3,10,5,25,2,8]
输出:28
解释:最大运算结果是 5 XOR 25 = 28.
示例 2:
输入:nums = [0]
输出:0
示例 3:
输入:nums = [2,4]
输出:6
示例 4:
输入:nums = [8,10,2]
输出:10
示例 5:
输入:nums = [14,70,53,83,49,91,36,80,92,51,66,70]
输出:127
提示:
1 <= nums.length <= 2 * 105
0 <= nums[i] <= 231 - 1
解题思路:
这道题是位操作,并且应用一个法则:如果 a ^ b = max 成立 ,max 表示当前得到的“最大值”, 那么一定有 max ^ b = a 成立。具体实现看代码。
代码实现:
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
ans = 0
# 掩码,位操作,用于获得前缀,初始化为0
mask = 0
# 因为 0 <= nums[i] <= 2的31次方 - 1
# 循环31次即可,为了获取最大值,所以从最高位开始操作
for i in range(30, -1, -1):
# 从高位开始获得掩码
mask |= (1 << i)
# 将前缀都放进一个哈希表中
s = set()
# 前缀的获取是通过掩码和数字本身进行按位与操作
# 前缀存到set中用于后面的异或结果查找
for num in nums:
s.add(mask & num)
# 假设最大的异或值的从高位开始是1
# 所以用ans按位或操作,获得一个临时异或最大值temp
# 去set中查找是否在num中存在一个数,和temp进行异或操作
# 使得当前的位是1
temp = ans | (1 << i)
# 然后根据法则:如果 a ^ b = max 成立 ,max 表示当前得到的“最大值”,
# 那么一定有 max ^ b = a 成立
# 此时temp看成是max,prefix看成是b,s中的值看成是a
for prefix in s:
if temp ^ prefix in s:
# 更新异或最大值
ans = temp
break
# 清空本次的前缀
s.clear()
return ans
参考文献:
https://leetcode.cn/problems/maximum-xor-of-two-numbers-in-an-array/solution/li-yong-yi-huo-yun-suan-de-xing-zhi-tan-xin-suan-f/
边栏推荐
猜你喜欢

El table implements editable table

How to build a customer-centric product blueprint: suggestions from the chief technology officer

如何构建以客户为中心的产品蓝图:来自首席技术官的建议

HCIP第十二天笔记整理(BGP联邦、选路规则)

解决远程主机无法连接mysql数据库的问题

Can I take your subdomain? Exploring Same-Site Attacks in the Modern Web

Seven steps to copywriting script ---- document team collaborative management

Photoshop(CC2020)未完
Control the probability of random winning [C | random]

With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
随机推荐
【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯
AI-理论-知识图谱1-基础
Ultimate doll 2.0 | cloud native delivery package
Detailed relation extraction model casrel
Multi objective optimization series 1 --- explanation of non dominated sorting function of NSGA2
key&key_ Len & ref & filtered (4) - MySQL execution plan (50)
B+树索引使用(8)排序使用及其注意事项(二十)
官宣!艾德韦宣集团与百度希壤达成深度共创合作
冒泡排序的时间复杂度分析
Leetcode 2119. number reversed twice
One stroke problem (Chinese postman problem)
Implementation of SAP ABAP daemon
The use of asynchronous thread pool in development
LeetCode 69. x 的平方根
Activity.onStop() 延迟10秒?精彩绝伦的排查历程
JS object assignment problem
Emotion analysis model based on Bert
Outline design specification
同站攻击(相关域攻击)论文阅读 Can I Take Your Subdomain?Exploring Same-Site Attacks in the Modern Web
Solve the problem that the remote host cannot connect to the MySQL database