Skip to content

Commit 1bfbf75

Browse files
committed
Runtime: 1588 ms (Top 85.61%) | Memory: 20.60 MB (Top 80.3%)
1 parent 171efbd commit 1bfbf75

File tree

1 file changed

+16
-41
lines changed

1 file changed

+16
-41
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,19 @@
1-
// Runtime: 9000 ms (Top 21.88%) | Memory: 36.5 MB (Top 15.63%)
2-
from collections import defaultdict
3-
4-
class TrieNode:
5-
def __init__(self):
6-
self.nodes = defaultdict(TrieNode)
7-
self.cnt = 0
8-
9-
class Trie:
10-
11-
def __init__(self):
12-
self.root = TrieNode()
13-
14-
def insert(self, val):
15-
cur = self.root
16-
for i in reversed(range(15)):
17-
bit = val >> i & 1
18-
cur.nodes[bit].cnt += 1
19-
cur = cur.nodes[bit]
20-
21-
def count(self, val, high):
22-
res = 0
23-
cur = self.root
24-
for i in reversed(range(15)):
25-
if not cur:
26-
break
27-
bit = val >> i & 1
28-
cmp = high >> i & 1
29-
if cmp:
30-
res += cur.nodes[bit].cnt
31-
cur = cur.nodes[1^bit]
32-
else:
33-
cur = cur.nodes[bit]
34-
return res
1+
// Runtime: 1588 ms (Top 85.61%) | Memory: 20.60 MB (Top 80.3%)
352

363
class Solution:
37-
def countPairs(self, nums: List[int], low: int, high: int) -> int:
38-
trie = Trie()
4+
def countPairs(self, nums, low, high):
5+
return self._countPairs(nums, high + 1) - self._countPairs(nums, low)
6+
7+
def _countPairs(self, nums, high):
398
res = 0
40-
for num in nums:
41-
res += trie.count(num, high + 1) - trie.count(num, low)
42-
trie.insert(num)
43-
44-
return res
9+
for k in range(31, -1, -1):
10+
target = high >> k
11+
if target & 1 == 0:
12+
continue
13+
target -= 1
14+
counter = Counter(num >> k for num in nums)
15+
for mask in counter:
16+
res += counter[mask] * counter[target ^ mask]
17+
if mask == target ^ mask:
18+
res -= counter[mask]
19+
return res // 2

0 commit comments

Comments
 (0)