leetcode 421. Maximum XOR of Two Numbers in an Array
来源:互联网 发布:淘宝运费险赔付多少钱 编辑:程序博客网 时间:2024/05/22 16:04
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: 28Explanation: The maximum result is 5 ^ 25 = 28.
class Solution {public: int findMaximumXOR(vector<int>& nums) { int ret = 0; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { ret = max(ret, nums[j] ^ nums[i]); } } return ret; }};
网上找了个bit的解法。
按位遍历,题目中给定了数字的返回不会超过2^31,那么最多只能有32位,
我们用一个从左往右的mask,用来提取数字的前缀,然后将其都存入set中,
我们用一个变量t,用来验证当前位为1再或上之前结果res,看结果和set中的前缀异或之后在不在set中,这里用到了一个性质,若a^b=c,那么a=b^c,因为t是我们要验证的当前最大值,所以我们遍历set中的数时,和t异或后的结果仍在set中,说明两个前缀可以异或出t的值,所以我们更新res为t,继续遍历,如果上述讲解不容易理解,那么建议自己带个例子一步一步试试,并把每次循环中set中所有的数字都打印出来,基本应该就能理解了
class Solution {public: int findMaximumXOR(vector<int>& nums) { int res = 0, mask = 0; for (int i = 31; i >= 0; --i) { mask |= (1 << i); set<int> s; for (int num : nums) { s.insert(num & mask); } int t = res | (1 << i); for (int prefix : s) { //证明set中存在一个数x使得 x ^ prefix = t 那t就是最新的最大的 if (s.count(t ^ prefix)) { res = t; break; } } } return res; }};
阅读全文
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 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】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
- JAVA基础-类1-面向对象概述
- Linux下VirtualBox虚拟机的命令行启动/关闭方法和开机自动启动
- Hive数据仓库之快速入门
- 大型企业分布式微服务云架构服务组件
- 流程框架
- leetcode 421. Maximum XOR of Two Numbers in an Array
- 关于HTML的一些知识(自己看)
- Netty入门官方例子
- 简单的Tensorflow(3):使用feed_dict字典填充
- 初识ZooKeeper。
- KNN近邻算法总结
- Jackson
- Android Bander设计与实现
- JS抽奖案列