forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
52 lines (48 loc) · 1.17 KB
/
Solution.cpp
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
class Trie {
public:
Trie()
: children(2)
, cnt(0) {}
void insert(int x) {
Trie* node = this;
for (int i = 15; ~i; --i) {
int v = x >> i & 1;
if (!node->children[v]) {
node->children[v] = new Trie();
}
node = node->children[v];
++node->cnt;
}
}
int search(int x, int limit) {
Trie* node = this;
int ans = 0;
for (int i = 15; ~i && node; --i) {
int v = x >> i & 1;
if (limit >> i & 1) {
if (node->children[v]) {
ans += node->children[v]->cnt;
}
node = node->children[v ^ 1];
} else {
node = node->children[v];
}
}
return ans;
}
private:
vector<Trie*> children;
int cnt;
};
class Solution {
public:
int countPairs(vector<int>& nums, int low, int high) {
Trie* tree = new Trie();
int ans = 0;
for (int& x : nums) {
ans += tree->search(x, high + 1) - tree->search(x, low);
tree->insert(x);
}
return ans;
}
};