(LeetCode) 421. Maximum XOR of Two Numbers in an Array

来源:互联网 发布:电脑主机 知乎 编辑:程序博客网 时间:2024/06/04 23:34

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: 28Explanation: The maximum result is 5 ^ 25 = 28.

代码

class Solution {public:    int findMaximumXOR(vector<int>& nums) {        int res = 0;        int mask = 0;        for (int i=31; i>=0;--i){            unordered_set<int> prefix_set;            mask = mask | (1<<i);            for (int n:nums){                prefix_set.insert(n&mask);            }            int tmp = res | (1<<i);            for (int prefix:prefix_set){                if (prefix_set.find(tmp^prefix)!=prefix_set.end()){                    res=tmp;                    break;                }            }        }        return res;    }};
原创粉丝点击