-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.cpp
52 lines (47 loc) · 1.04 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 BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n): n(_n), c(_n + 1){}
void update(int x, int delta) {
while (x <= n)
{
c[x] += delta;
x += lowbit(x);
}
}
int query(int x) {
int s = 0;
while (x > 0)
{
s += c[x];
x -= lowbit(x);
}
return s;
}
int lowbit(int x) {
return x & -x;
}
};
class Solution {
public:
int reversePairs(vector<int>& nums) {
set<long long> s;
for (int num : nums)
{
s.insert(num);
s.insert(num * 2ll);
}
unordered_map<long long, int> m;
int idx = 0;
for (long long num : s) m[num] = ++idx;
BinaryIndexedTree* tree = new BinaryIndexedTree(m.size());
int ans = 0;
for (int i = nums.size() - 1; i >= 0; --i)
{
ans += tree->query(m[nums[i]] - 1);
tree->update(m[nums[i] * 2ll], 1);
}
return ans;
}
};