421 Maximum XOR of Two Numbers in an Array
1. Question
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai< 231.
Find the maximum result of aiXOR 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.2. Implementation
(1) Brute Force
class Solution {
public int findMaximumXOR(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
max = Math.max(max, nums[i] ^ nums[j]);
}
}
return max;
}
}(2) Bit Manipulation + Trie
3. Time & Space Complexity
Brute Force: 时间复杂度O(n^2), 空间复杂度O(1)
Bit Manipulation + Trie: 时间复杂度O(n), 空间复杂度O(n)
Last updated
Was this helpful?