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<Integer> set = new HashSet<Integer>();
            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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容