-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreversePairs-bit.cc
More file actions
35 lines (32 loc) · 951 Bytes
/
reversePairs-bit.cc
File metadata and controls
35 lines (32 loc) · 951 Bytes
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
class Solution {
public:
void update(vector<int>& BIT, int index, int val)
{
while (index > 0) {
BIT[index] += val;
index -= index & (-index);
}
}
int query(vector<int>& BIT, int index)
{
int sum = 0;
while (index < BIT.size()) {
sum += BIT[index];
index += index & (-index);
}
return sum;
}
int reversePairs(vector<int>& nums)
{
int n = nums.size();
vector<int> nums_copy(nums);
sort(nums_copy.begin(), nums_copy.end());
vector<int> BITS(n + 1, 0);
int count = 0;
for (int i = 0; i < n; i++) {
count += query(BITS, lower_bound(nums_copy.begin(), nums_copy.end(), 2LL * nums[i] + 1) - nums_copy.begin() + 1);
update(BITS, lower_bound(nums_copy.begin(), nums_copy.end(), nums[i]) - nums_copy.begin() + 1, 1);
}
return count;
}
};