Maximum XOR of Two Numbers in an Array (M)
題目
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.
題意
在陣列中選取兩個數進行異或,求能夠得到的最大值,
思路
解題需要用到異或的性質:x^b=a => x^b^b=a^b => a^b=x,為了得到最大值,應使最終結果ans的高位盡可能為1,從第32位向第1位遍歷,每次取出所有數到當前位的前綴,存入到HashSet中;x由上一次遍歷得到的ans將當前位設為1得到,將x與任意一個前綴b異或,如果得到的結果a也在HashSet中,說明存在兩個前綴異或能夠得到x,因此ans當前位確實為1,用x更新ans,否則ans保持不變(即當前位保持為1),可以看到每次遍歷的作用是確定了最終數在相應位是0還是1,
代碼實作
Java
class Solution {
public int findMaximumXOR(int[] nums) {
int ans = 0;
int mask = 0;
for (int i = 31; i >= 0; i--) {
Set<Integer> set = new HashSet<>();
mask |= 1 << i;
for (int num : nums) {
int prefix = mask & num;
int tmp = (1 << i) | ans;
if (set.contains(tmp ^ prefix)) {
ans = tmp;
break;
}
set.add(prefix);
}
}
return ans;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/60980.html
標籤:其他
上一篇:ifconfig講解(ip地址)
下一篇:騰訊云推出云原生etcd服務
