Skip to content

Commit e0a87eb

Browse files
committed
1803
1 parent ff55dd9 commit e0a87eb

File tree

1 file changed

+50
-0
lines changed
  • leetcode/1803. Count Pairs With XOR in a Range

1 file changed

+50
-0
lines changed

leetcode/1803. Count Pairs With XOR in a Range/README.md

+50
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,54 @@ public:
9393
return ans;
9494
}
9595
};
96+
```
97+
98+
## Solution 2. Trie
99+
100+
```cpp
101+
// OJ: https://leetcode.com/problems/count-pairs-with-xor-in-a-range/
102+
// Author: github.com/lzl124631x
103+
// Time: O(N)
104+
// Space: O(1)
105+
struct TrieNode {
106+
TrieNode *next[2] = {};
107+
int cnt = 0;
108+
};
109+
const int BIT = 15;
110+
class Solution {
111+
void addNode(TrieNode *node, int n) {
112+
for (int i = BIT; i >= 0; --i) {
113+
int b = n >> i & 1;
114+
if (!node->next[b]) node->next[b] = new TrieNode();
115+
node = node->next[b];
116+
node->cnt++;
117+
}
118+
}
119+
int countLessThan(TrieNode *node, int n, int limit) {
120+
int ans = 0;
121+
for (int i = BIT; i >= 0 && node; --i) {
122+
int b = n >> i & 1, r = 1 - b, lb = limit >> i & 1;
123+
if (lb == 1) {
124+
if (node->next[b]) ans += node->next[b]->cnt;
125+
node = node->next[r];
126+
} else {
127+
node = node->next[b];
128+
}
129+
}
130+
return ans;
131+
}
132+
int count(TrieNode *node, int n, int low, int high) {
133+
return countLessThan(node, n, high + 1) - countLessThan(node, n, low);
134+
}
135+
public:
136+
int countPairs(vector<int>& A, int low, int high) {
137+
TrieNode root;
138+
int ans = 0;
139+
for (int n : A) {
140+
ans += count(&root, n, low, high);
141+
addNode(&root, n);
142+
}
143+
return ans;
144+
}
145+
};
96146
```

0 commit comments

Comments
 (0)