Leetcode Maximum XOR of Two Numbers in an Array
2017-03-28 00:44
405 查看
题意:给出一列数组,求出其中两个数字异或的最大值。
思路:这题的思路很巧妙,枚举了每个位上的数字。又利用的异或的性质。
当查询某个数是否存在时,可以用字典树,而不是用map。
思路:这题的思路很巧妙,枚举了每个位上的数字。又利用的异或的性质。
class Solution { public: int findMaximumXOR(vector<int>& nums) { int mask = 0; int re = 0; for(int i = 31; i >=0; -- i) { mask |= (1 << i); map<int, bool> prefix; for(int j = 0; j < nums.size(); ++ j) { prefix[mask & nums[j]] = true; } int temp = re; temp |= (1 << i); for(int j = 0; j < nums.size(); ++ j) { if(prefix[temp ^ (nums[j] & mask)]) re = temp; } } return re; } };
当查询某个数是否存在时,可以用字典树,而不是用map。
class Solution { public: int findMaximumXOR(vector<int>& nums) { TrieTree* root = buildTrieTree(nums); //root = root->buildTrieTree(nums); int re = 0; for(int i = 0; i < nums.size(); ++ i) { re = max(re, findIt(root, nums[i])); } return re; } private: class TrieTree { public: TrieTree* c[2]; TrieTree() { c[0] = NULL, c[1] = NULL; }; }; TrieTree* buildTrieTree(vector<int> nums) { TrieTree* root = new TrieTree(), *next = NULL; for(int i = 0; i < nums.size(); ++ i) { int num = nums[i]; //cout << num << endl; next = root; for(int j = 31; j >=0; --j) { bool bit = (num >> j) & 1; //cout <<num << ((num >>= j) & 1) << endl; if(next->c[bit]) { next = next->c[bit]; } else { TrieTree* child = new TrieTree(); next->c[bit] = child; next = child; } } } return root; } int findIt(TrieTree* root, int num) { int re = 0; int rnum = ~num; for(int i = 31; i >=0; -- i) { bool bit =(rnum >> i) & 1; if(root->c[bit]) { re |= (1 << i); root = root->c[bit]; } else { root = root->c[!bit]; 4000 } } return re; } };
相关文章推荐
- LeetCode Maximum XOR of Two Numbers in an Array
- LeetCode 421 Maximum XOR of Two Numbers in an Array 解题报告
- 前缀树及应用两数异或Leetcode之 Maximum XOR of Two Numbers in an Array
- 【LeetCode-421】Maximum XOR of Two Numbers in an Array
- [LeetCode] Maximum XOR of Two Numbers in an Array 数组中异或值最大的两个数字
- Leetcode: Maximum XOR of Two Numbers in an Array
- Maximum XOR of Two Numbers in an Array问题及解法
- LeetCode #421: Maximum XOR of Two Numbers in an Array
- Maximum XOR of Two Numbers in an Array--异或、字典树
- Maximum XOR of Two Numbers in an Array
- Trie (3) -- Maximum XOR of Two Numbers in an Array
- Maximum XOR of Two Numbers in an Array
- 【特别好】【位运算】maximum-xor-of-two-numbers-in-an-array
- Leetcode 421. Maximum XOR of Two Numbers in an Array 最大Xor和 解题报告【待理解】
- [leetcode]421. Maximum XOR of Two Numbers in an Array
- [leetcode] 421. Maximum XOR of Two Numbers in an Array 解题报告
- [LeetCode] 421. Maximum XOR of Two Numbers in an Array(位操作)
- trie树-leetcode-421. Maximum XOR of Two Numbers in an Array
- leetcode 421. Maximum XOR of Two Numbers in an Array
- leetcode题解Java | 421. Maximum XOR of Two Numbers in an Array