LeetCode #421: Maximum XOR of Two Numbers in an Array
来源:互联网 发布:.club域名与.com 编辑:程序博客网 时间:2024/06/05 07:34
Problem Statement
(Source) Given a non-empty array of numbers,
Find the maximum result of
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.
Solution
Tags: Trie
, Bit Manipulation
.
Self-explained code is as follows. The time complexity is
class Solution(object): def findMaximumXOR(self, nums): """ :type nums: List[int] :rtype: int """ arr = map(lambda x: bin(x)[2:].rjust(32, '0'), nums) pt = {} # prefix tree def add(pt, x): for i in xrange(len(x)): if x[i] not in pt: pt[x[i]] = {} pt = pt[x[i]] def calculate(pt, x): t = [] for i in xrange(len(x)): keys = pt.keys() if len(keys) == 1: if x[i] in keys: t.append('0') else: t.append('1') pt = pt[keys.pop()] else: keys.remove(x[i]) t.append('1') pt = pt[keys.pop()] return int(''.join(t), base=2) res = 0 add(pt, arr[0]) for i in xrange(1, len(arr)): res = max(res, calculate(pt, arr[i])) add(pt, arr[i]) return res
1 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 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: 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 解题报告
- 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
- 洛谷P2658 汽车拉力比赛
- 构造器内部的多态方法
- STL: insert和copy用法汇总
- Pycharm中创建的flask项目,不能关联Jinja2模版的问题解决
- C 字符串数组冒泡排序
- LeetCode #421: Maximum XOR of Two Numbers in an Array
- Ubuntu系统下为 intelliJ idea添加启动项,直接在dash中启动即可
- input name and value and type
- Java线程的学习_线程的生命周期
- 6.2 Python class 继承
- 2016 杭州·云栖大会 PDF 下载的一个分享
- 大字符串Remove,Replace方法不適用,導致內存溢出
- 聆听巴赫
- python数据结构学习笔记-2016-10-28-01-带尾指针的链表和排序链表