421. Maximum XOR of Two Numbers in an Array详解
来源:互联网 发布:推广产品的软件 编辑:程序博客网 时间:2024/05/16 02:05
题目:
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: 28
Explanation: The maximum result is 5 ^ 25 = 28
代码:
#include<iostream>
#include<set>
using namespace std;
int findMaximumXOR(int *nums,int a) {
set<int>::iterator it1;
for(int i=0; i<6; i++){
cout<<nums[i]<<endl;
}
int max = 0, mask = 0;
for(int i = 31; i >= 0; i--){
mask = mask | (1 << i);
set<int> set1;
for(int j=0; j<6; j++){
// cout<<"nums[i]="<<nums[i]<<"; mask="<<mask<<"; nums[i]&mask="<<(nums[i]&mask)<<endl;
set1.insert(nums[j] & mask);
}
cout<<"bianli start;"<<endl;
for (it1 = set1.begin(); it1 != set1.end(); ++it1)
{
cout << *it1 << endl;
}
cout<<"bianli end;"<<endl;
int tmp = max | (1 << i);
for(set<int>::iterator it = set1.begin(); it != set1.end();it++){
if(set1.end()!=set1.find(tmp ^ (*it))) {
cout<<"tmp="<<tmp<<"; tmp^(*it)="<<(tmp^(*it))<<"; *it="<<(*it)<<endl;
max = tmp;
break;
}
}
cout<<endl;
}
return max;
};
int main(){
int nums[] = {
2,3,5,10,8,25
};
int max = findMaximumXOR(nums,6);
cout<<max;
}
解释:通过mask从左往右和nums中的数&,mask从左往右依次增加1位。
set1中的数据为nums中的数分别与mask &之后的值,即nums中的数被从左往右依次处理。
tmp为当前max和新的一位或运算,然后通过下面的循环判断tmp是否为合适的max
如果tmp能与set1中的某一个数异或后还存在于set1中的话,那么set1中的这两个相关数异或后就可以成为tmp,即当前最大值。然后就可以把它赋值给max。
这里用了异或的自反性,即 a ^ b = c,而a ^ b ^ b = a, 则 c ^ b = a。理解这一点很重要。
说明:我的代码只是用于例子,不具有通用性,需要改一改。
1 0
- 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
- 【LeetCode】 421. Maximum XOR of Two Numbers in an Array
- 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
- Leetcode-421. Maximum XOR of Two Numbers in an Array
- 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
- 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
- 【15.93%】【codeforces 672D】Robin Hood
- 当在64位linux编译uboot的时候会提示很多so没有
- 【部署】bitnami快速部署mantis、gerrit
- monkey测试环境搭建
- Java中的访问控制符与修饰符浅析
- 421. Maximum XOR of Two Numbers in an Array详解
- java图片文字识别技术
- 【栈应用】迷宫问题
- 在ubuntu14.04上安装mysql
- Redis的哨兵机制
- Spyder3更新和更新后碰到的图标变化问题
- [转]PHP函数的实现原理及性能分析
- 【Java】中类的构造方法与类中创建其他类对象的先后顺序
- 标签添加中划线