Leetcode Maximum XOR of Two Numbers in an Array
来源:互联网 发布:java 自动生成代码 编辑:程序博客网 时间:2024/06/05 08:54
题意:给出一列数组,求出其中两个数字异或的最大值。
思路:这题的思路很巧妙,枚举了每个位上的数字。又利用的异或的性质。
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]; } } return re; }};
0 0
- 【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
- 【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
- [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) 421. 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 421. Maximum XOR of Two Numbers in an Array
- 421. Maximum XOR of Two Numbers in an Array详解
- 421. Maximum XOR of Two Numbers in an Array
- 421. Maximum XOR of Two Numbers in an Array
- 421. Maximum XOR of Two Numbers in an Array
- linux练习题4
- 1012. 数字分类 (20)-PAT乙级
- LintCode-删除排序链表中的重复元素
- POJ 1321
- 初识Markdown
- Leetcode Maximum XOR of Two Numbers in an Array
- LintCode-删除链表中倒数第n个节点
- [LeetCode]506. Relative Ranks
- 三种创建节点的方法
- va_start和va_end使用详解
- sqlcookbook小结C1-C2
- LintCode-两两交换链表中的节点
- SLAM笔记(一)数学基础
- 自定义Dialog