Two elements in array whose xor is maximum

后端 未结 6 1548
野趣味
野趣味 2020-12-22 16:35

Given an array of integers ,You have to find two elements whose XOR is maximum.

There is naive approach --just by picking each element and xoring with other elemen

6条回答
  •  鱼传尺愫
    2020-12-22 17:15

    A very interesting problem! Here is my idea:

    • First build a binary tree from all the numbers by using the binary representation and sort them into the tree most significant bit first (add leading zeros to match the longest number). When done each path from the root to any leaf represents one number from the original set.
    • Let a and b be pointers to a tree node and initialize them at the root.
    • Now move a and b down the tree, trying to use opposite edges at each step, i.e. if a moves down a 0-edge, b moves down a 1-edge unless its not possible.

    If a and b reach a leaf, the should point to two numbers with "very few" identical bits.

    I just made this algorithm up and do not know if its correct or how to prove it. However it should be in O(n) running time.

提交回复
热议问题