[leetcode] 421. Maximum XOR of Two Numbers in an Array 解题报告

来源:互联网 发布:手机mac地址伪装 编辑:程序博客网 时间:2024/06/07 14:10

题目链接: https://leetcode.com/problems/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 ≤ ij < 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:    struct Trie{        vector<Trie*> child;        Trie():child(vector<Trie*>(2, NULL)){}    };        void add(int num){        Trie* tem = root;        for(int i = 31; i >=0; i--){            int val = (num>>i)&1;            if(!tem->child[val]) tem->child[val] = new Trie();            tem = tem->child[val];        }    }        int search(int num){        int ans = 0;        Trie* tem = root;        for(int i = 31; i >= 0; i--){            int val = (num>>i)&1;            ans = ans<<1;            if(tem->child[val]) ans++, tem = tem->child[val];            else tem = tem->child[!val];        }        return ans;    }        int findMaximumXOR(vector<int>& nums) {        root = new Trie();        for(auto val: nums) add(val);        int ans = INT_MIN;        for(auto val: nums) ans = max(ans, search(~val));        return ans;    }private:    Trie *root;};


0 0
原创粉丝点击