421. Maximum XOR of Two Numbers in an Array

Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ ij < n.

Could you do this in O(n) runtime?

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.
含义:给定一个非空数组,任意两个整数做异或操作,找到最大的异或值
复制代码
 1     public int findMaximumXOR(int[] nums) {
 2         int max = 0, mask = 0;
 3         // test each bit pose, 判断能不能构成所需要的值;
 4         for(int i = 31; i >= 0; i --) {
 5             // 每次都在之前的基础上更新mask
 6             mask = mask | (1 << i); //用来累加获取每个数的前N位
 7             Set<Integer> set = new HashSet<>();
 8             for(int num : nums) {
 9                 // add the number which has the mask as its prefix;
10                 set.add(num & mask);
11             }
12             // 假设当前所能达到的最大值是这个temp值;
13             int tmp = max | (1 << i);//用来获取最大值的前N位
14             for(Integer prefix : set) {
15                 // 利用了 ^ 的 prefix ^ tmp = c,则 prefix ^ c = temp
16                 if(set.contains(prefix ^ tmp)) {
17                     // 如果能组成就直接break
18                     max = tmp;
19                     break;
20                 }
21             }
22         }
23         return max;      
24     }
复制代码

 

posted @   daniel456  阅读(122)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示