421. 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 ≤ 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值