码迷,mamicode.com
首页 > 其他好文 > 详细

【特别好】【位运算】maximum-xor-of-two-numbers-in-an-array

时间:2016-10-16 13:54:22      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/

利用了异或的”自反性“: a ^ b = c,而a ^ b ^ b = a, 则 c ^ b = a

其他运算定律有:交换律、结合律、分配律。

// 非常非常棒
// 参考了 https://discuss.leetcode.com/topic/63213/java-o-n-solution-using-bit-manipulation-and-hashmap
// 特别的,利用了异或的强大运算特性,见22行,来加速运算

public class Solution {
        public int findMaximumXOR(int[] nums) {
        int max = 0;
        int flag = 0;
        
        // from left to right
        for (int i=31; i>=0; i--) {
            Set<Integer> prefixSet = new HashSet();
            // flag : 11110000
            flag = flag | (1<<i);
            for (int num : nums) {
                prefixSet.add(num & flag);
            }

            // tmp, max: 10101000000, add more 1 
            int tmp = max | (1<<i);
            for (int prefix : prefixSet) {
                // 利用了 ^ 的 a ^ b = c,则 b ^ c = a
                if (prefixSet.contains(tmp ^ prefix)) {
                    max = tmp;
                    break;
                }
            }
        }
        return max;
    }
}

 

【特别好】【位运算】maximum-xor-of-two-numbers-in-an-array

标签:

原文地址:http://www.cnblogs.com/charlesblc/p/5966368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!