如果按照暴力的方法,进行两次循环可以解决:
for i in range(N):
for j in range(i+1, N):
ans = max(ans,nums[i]^nums[j])
这样操作的时间复杂度为 O ( n ) O(n) O(n)
还可以转化为二进制的问题,进而用Trie树解决。我们从最高位开始进行选择,尽量选择与目前这个数不同的位,这样可以保证异或最大。
class Trie:
def __init__(self):
self.dic = {}
def add(self, x):
dic = self.dic
i = 30
while i >= 0:
cur = (x>>i) & 1
if cur not in dic:
dic[cur] = {}
dic = dic[cur]
i -= 1
def query(self, x):
dic = self.dic
i = 30
ans = 0
while i >= 0:
cur = (x>>i)&1
if 1-cur in dic:
dic = dic[1-cur]
#ans = ans * 2 + 1-cur
ans += 1<<i
else:
#ans = ans * 2 + cur
dic = dic[cur]
i -= 1
return ans
N = int(input())
good = list(map(int, input().split()))
tree = Trie()
max_ = 0
for i in range(N):
tree.add(good[i]) # 先插入,可以避免判断空树
ans = tree.query(good[i])
max_ = max(max_, ans)
print(max_)