LeetCode 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 ≤ i, j < 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.
Subscribe to see which companies asked this question.
对应链接为:https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/#/description

解题思路:

1.由于是异或的最大值,必然需要从高位开始寻找,也就是说所有数据里面的最高位是否是最终结果。
2.这道题采用位运算里面的尝试判断,其实就是遍历所有情况,从当前数据的最高位开始,每一次都需要判断当前值是否可以有当前所有值的异或计算得出。由于在查找过程中,直接使用set,所以时间复杂度符合题目要求。

具体代码如下:

public class Solution {
    public int findMaximumXOR(int[] nums) {
        int max = 0;
        int mask = 0;
        for(int i=31;i>=0;i--){
            mask = mask | (1<<i); //主要作用是用来选取所有数的最高位
            Set<Integer> set = new HashSet<>();
            for(int num : nums){
                set.add(num & mask);  //与操作选取最高位
            }
            int temp = max | (1<<i); //假设当前最高位的值是可以异或计算得到的结果。然后从高位开始试,一个一个尝试是不是可以由两个数值异或得到
            for(int num : set){
                if(set.contains(temp ^ num)){//如果存在两个数异或得到该值,则保留该位为1,结束。否则该位为0.
                    max = temp;
                    break;
                }
            }
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值