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.

Solution:

思路:
从最高位开始,统计nums各元素在此位的值是1是0,依次mask从10000, 11000, 11100 ...
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

public class Solution {
    public int findMaximumXOR(int[] nums) {
        int max = 0, mask = 0;
        for (int i = 31; i >= 0; i--) {
            mask |= (1 << i); // ex, mask: 10000 -> 11000 -> 11100 -> 11110 -> 11111
            HashSet set = new HashSet();
            for (int num : nums) {
                set.add(num & mask); // reserve Left bits and ignore Right bits
            }
            
            /* Use 0 to keep the bit, 1 to find XOR
             * 0 ^ 0 = 0 
             * 0 ^ 1 = 1
             * 1 ^ 0 = 1
             * 1 ^ 1 = 0
             */
            int tmp = max | (1 << i); // 假装能达到最大1,左边的位从max结果保留
             // in each iteration, there are pair(s) whose Left bits can XOR to max
            for (int prefix : set) {
                if (set.contains(tmp ^ prefix)) { // a ^ b = c, b ^ c = a, c ^ a = b, 看set(候选输入)有没有这样的输入能达到tmp
                    max = tmp;
                }
            }
        }
        return max;
    }
}

你可能感兴趣的:(421. Maximum XOR of Two Numbers in an Array)