[LeetCode] 421. Maximum XOR of Two Numbers in an Array(位操作)

传送门

Description

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 ≤ ij < 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.

思路

题意:给定一个数组,在时间复杂度为O(n)条件下求出两数异或的最大值

题解:此方法挺巧妙的,根据异或的性质,如果 a ^ b = c,那么a = b ^ c,因此我们利用这个性质,从高位开始枚举每个数的二进制位的前缀保存下来,然后在每一轮枚举前缀的时候也正好枚举答案,然后再在这些保存下来的前缀中查找是否有两数x, y 异或得到我们枚举的答案。

 

class Solution {
public:
    //162ms
    int findMaximumXOR(vector<int>& nums) {
        int res = 0,mask = 0;
        for (int i = 31;i >= 0;i--){
            mask |= (1 << i);
            set<int>prefix;
            for (unsigned int i = 0;i < nums.size();i++){
                prefix.insert(nums[i] & mask);
            }
            int tmp = res | (1 << i);          //从高位枚举答案

            //set中的数相当于a、b,tmp相当于c,我们根据tmp和set中已有的一个数异或,
            //如果得到的数也在set中,说明这两个数异或能得到tmp值,然后用tmp更新res
            for (set<int>::iterator it = prefix.begin();it != prefix.end();it++){
                if (prefix.count(tmp^*it)){
                    res = tmp;
                    break;
                }
            }
        }
        return res;
    }
};

  

posted @ 2017-08-19 23:22  zxzhang  阅读(253)  评论(0编辑  收藏  举报