1. 程式人生 > 實用技巧 >0421. Maximum XOR of Two Numbers in an Array (M)

0421. Maximum XOR of Two Numbers in an Array (M)

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;
    }
}