-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path421_maxXOR.py
More file actions
55 lines (50 loc) · 1.7 KB
/
Copy path421_maxXOR.py
File metadata and controls
55 lines (50 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution:
def findMaximumXOR(self, nums):
"""
Solution 1 -- time limit exceeded
First, find the longest "num"s in binary form.
Second, set their last "masklen" digits into 1 and then find the largest one.
This one must be chose to get largest XOR result.
At last, travel the "nums" to find the pair having max XOR result within O(N) time limit
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
maxlen = -1 # max length
maxlen2 = -1 # second max length
maxnums = []
for num in nums:
num_ = str(bin(num))[2:]
length = len(num_)
if length == maxlen:
maxnums.append(num)
elif length > maxlen:
maxnums = [num]
maxlen2 = maxlen
maxlen = length
else:
if length > maxlen2:
maxlen2 = length
# print(maxlen)
# print(maxlen2)
if maxlen2 == -1:
cands = maxnums
else:
masklen = maxlen2 # 2nd max length
cands = [int(x/(2**masklen)) for x in maxnums] # use mask to remove the difference in last masklen binary digits
maxcand = max(cands) # get the max candidate
result = -1
for cand, num in zip(cands, maxnums):
if cand == maxcand:
for x in nums:
if num^x > result:
result = num^x
return result
class Solution2:
def findMaximumXOR(self, nums):
pass
if __name__ == '__main__':
nums = [8, 10, 2]
s = Solution()
print(s.findMaximumXOR(nums))