421. Maximum XOR of Two Numbers in an Array
2017-07-22 21:45
260 查看
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?
之后遍历每个数,找出尽可能多的不同位的另一个数,进行异或,记录最大值
空间复杂度O(n),时间复杂度O(n)
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
题解
使用trie树记录所有数的01二进制表示之后遍历每个数,找出尽可能多的不同位的另一个数,进行异或,记录最大值
空间复杂度O(n),时间复杂度O(n)
class Trie { Trie[] children; public Trie() { children = new Trie[2]; } } public class Solution { public int findMaximumXOR(int[] nums) { if(nums.length <= 1) return 0; //用trie存储所有数的二进制表达 Trie root = new Trie(); for(int num: nums) { Trie curNode = root; for(int i = 31; i >= 0; i --) { int curBit = (num >>> i) & 1; if(curNode.children[curBit] == null) { curNode.children[curBit] = new Trie(); } curNode = curNode.children[curBit]; } } int max = Integer.MIN_VALUE; for(int num: nums) { Trie curNode = root; int curSum = 0; for(int i = 31; i >= 0; i --) { int curBit = (num >>> i) & 1; //尽可能取对应位相反 if(curNode.children[curBit ^ 1] != null) { curSum += (1 << i); curNode = curNode.children[curBit ^ 1]; }else { curNode = curNode.children[curBit]; } } max = Math.max(curSum, max); } return max; } }
相关文章推荐
- 【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 解题报告
- trie树-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 解题报告(Python)
- 421. Maximum XOR of Two Numbers in an Array
- 【特别好】【位运算】maximum-xor-of-two-numbers-in-an-array
- Finding sum of every combination of two numbers in an array in Ruby
- Leetcode: Maximum XOR of Two Numbers in an Array
- 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
- leetcode题解Java | 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
- Maximum XOR of Two Numbers in an Array--异或、字典树
- Leetcode 421. Maximum XOR of Two Numbers in an Array 最大Xor和 解题报告【待理解】
- 421. Maximum XOR of Two Numbers in an Array