剑指 Offer II 067. 最大的异或 - 力扣(LeetCode)
x为数组前K位的最大异或,一开始是0。
第一步:先将32位的数字分为前后两个部分,k分别取2,3...... 32
使用哈希结构将数组中的数字的前K位全部储存起来。
第二步:x = x* 2 + 1 ,只要判断是否在哈希结构中有x = a ^ b就行,
如果有x = x * 2 + 1;
否则x = x * 2
以此类推,最终得到x为前32位的最大异或,就是最终答案。
还有一个字典树解法:官方写的题解比较详细就不多说了。
class Solution {
public:
int findMaximumXOR(vector<int>& nums) {
int x = 0;
for(int i = 30; i >= 0; --i)
{
//store The first K bits of the date of nums
unordered_set<int> us;
for(auto& n : nums)
{
us.insert(n >> i);
}
//suppose The first K bits of x
x = x << 1;
++x;
bool flag = false;
for(auto& n : nums)
{
if(us.count(x ^ (n >> i)))
{
flag = true;
break;
}
}
if(!flag)
{
--x;
}
}
return x;
}
};