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 ≤ 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.
問題描述
給定非空陣列,
a_0, a_1, a_2, , ...a_{n - 1}, 0 < a_i < 2^{31}
找出
a_i
與a_j
異或的最大值, 0 <= i, j < n
你能以O(n)的時間複雜度完成麼
解法
public class Solution {
public int findMaximumXOR(int[] nums) {
int max = 0, mask = 0;
for(int i = 31; i >= 0; i--){
//最高位置為1(注意, 若上一輪可以達到, 那麼這一輪會在以後累計置1)
mask = mask | (1 << i);
Set<Integer> set = new HashSet<>();
//獲取當前元素, 當前累計的最高位對應的值, 如, 若最高位為11(那麼獲取元素對應位元素)
for(int num : nums) set.add(num & mask);
//tmp為可能的當前最大值
int tmp = max | (1 << i);
for(int prefix : set){
//若滿足該條件, 說明存在兩個元素的異或滿足當前最高位
if(set.contains(tmp ^ prefix)) {
max = tmp;
break;
}
}
}
return max;
}
}
相關文章
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode-2 Add Two NumbersLeetCode
- LeetCode 2. Add Two NumbersLeetCode
- Add_Two_Numbers python 求解Python
- Find All Numbers Disappeared in an ArrayAPP
- abc098D Xor Sum 2(two point)
- LeetCode2: Add two numbers(兩數相加)LeetCode
- LeetCode 448. Find All Numbers Disappeared in an ArrayLeetCodeAPP
- Fifth. LeetCode 2:Add Two Numbers 兩數之和LeetCode
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- leetcode 兩數相加(add two numbers) Python程式設計實現LeetCodePython程式設計
- 2018-08-12 non-adjacent max two-number sum in loop arrayOOP
- BUUCTF xor
- Reversed Numbers
- 400多種Numbers模板 DesiGN for Numbers Templates for macMac
- buuctf 逆向 xor
- Collecting Numbers II
- Codeforces - Jzzhu and Numbers
- B. XOR = Average
- Trees and XOR Queries AgainAI
- B. Equal XOR
- coca after two months vs in two months
- different random numbers generatorrandom
- 7.39 BIT_XOR_AGG
- 【Lintcode】1267. Lexicographical Numbers
- 829. Consecutive Numbers Sum
- 165. Compare Version Numbers
- Leetcode 165 Compare Version NumbersLeetCode
- 201-Bitwise AND of Numbers Range
- [AGC061E] Increment or XORGCREM
- [ARC146C] Even XOR
- [ABC150F] Xor Shift
- 異或運算 XOR 教程
- Two Pirates - 2
- Two Pointer Method
- Array.from和 Array.of
- CF1406E Deleting Numbers