[LeetCode] 421. Maximum XOR of Two Numbers in an Array(位操作)

传送门

Description

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 ≤ ij < n.

Could you do this in O(n) runtime?

Example:

1
2
3
4
5
Input: [3, 10, 5, 25, 2, 8]
 
Output: 28
 
Explanation: The maximum result is 5 ^ 25 = 28.

思路

题意:给定一个数组,在时间复杂度为O(n)条件下求出两数异或的最大值

题解:此方法挺巧妙的,根据异或的性质,如果 a ^ b = c,那么a = b ^ c,因此我们利用这个性质,从高位开始枚举每个数的二进制位的前缀保存下来,然后在每一轮枚举前缀的时候也正好枚举答案,然后再在这些保存下来的前缀中查找是否有两数x, y 异或得到我们枚举的答案。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
    //162ms
    int findMaximumXOR(vector<int>& nums) {
        int res = 0,mask = 0;
        for (int i = 31;i >= 0;i--){
            mask |= (1 << i);
            set<int>prefix;
            for (unsigned int i = 0;i < nums.size();i++){
                prefix.insert(nums[i] & mask);
            }
            int tmp = res | (1 << i);          //从高位枚举答案
 
            //set中的数相当于a、b,tmp相当于c,我们根据tmp和set中已有的一个数异或,
            //如果得到的数也在set中,说明这两个数异或能得到tmp值,然后用tmp更新res
            for (set<int>::iterator it = prefix.begin();it != prefix.end();it++){
                if (prefix.count(tmp^*it)){
                    res = tmp;
                    break;
                }
            }
        }
        return res;
    }
};

  

posted @   zxzhang  阅读(254)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2016-08-19 树状数组求第k小的元素
点击右上角即可分享
微信分享提示

目录导航