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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-xor-of-two-numbers-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

从最高位开始,计算每一位所能达到的最大值。

如[3, 10, 5, 25, 2, 8],最高位是第五位,25,即11001,则最高位开始。

最高位5,理论上能达到的最大值为10000,即16。取数组剩下所有数字的第5位,看是否存在两个数字异或能达到10000。

到第4位,理论上能达到的最大值为11000,即24,取数组剩下所有数字的第4,5位,看是否存在两个数字异或能达到11000。

class Solution {
    public int findMaximumXOR(int[] nums) {
        int mask = 0;
        int ans = 0;
        int tmp = 0;
        for (int i = 31; i >= 0; i--) {
            // 1000 --> 1100 --> 1110 --> 1111
            mask = (mask) | 1 << i;
            Set set = new HashSet();
            for (int num : nums) {
                // 对每个数字,都取头几位,放入set
                set.add(num & mask);
            }
            //  对于遍历的到的第i位,tmp为这一位所能理论达到的最大值。
            tmp = (ans) | (1 << i);
            for (int num: set) {
                // a^b=c  则必有  a^c=b
                // 如果在set中有一个num,跟tmp异或后,还在set中,那么必有两个数字,可以异或成tmp。所以当前能达到理论上的最大值
                if (set.contains(num ^ tmp)) {
                    ans = tmp;
                    break;
                }
            }
        }
        return ans;
    }
}

 

你可能感兴趣的:(LEETCODE,Java)