-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse_Pairs.cpp
59 lines (56 loc) · 1.58 KB
/
Reverse_Pairs.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
53
54
55
56
57
58
59
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void merge(vector<int>& A, int low, int mid, int high) {
vector<int> ans;
int left = low;
int right = mid + 1;
while (left <= mid && right <= high) {
if (A[left] <= A[right]) {
ans.push_back(A[left]);
left++;
} else {
ans.push_back(A[right]);
right++;
}
}
while (left <= mid) {
ans.push_back(A[left]);
left++;
}
while (right <= high) {
ans.push_back(A[right]);
right++;
}
for (int i = low; i <= high; i++) {
A[i] = ans[i - low];
}
}
int countPairs(vector<int>& A, int low, int mid, int high) {
int cnt = 0;
int right = mid + 1;
for (int i = low; i <= mid; i++) {
while (right <= high && A[i] > (long)2 * A[right])
right++;
cnt += (right - (mid + 1));
}
return cnt;
}
int mergeSort(vector<int>& A, int low, int high) {
int cnt = 0;
int mid;
if (low >= high)
return 0;
mid = (low + high) / 2;
cnt += mergeSort(A, low, mid);
cnt += mergeSort(A, mid + 1, high);
cnt += countPairs(A, low, mid, high);
merge(A, low, mid, high);
return cnt;
}
int reversePairs(vector<int>& nums) {
return mergeSort(nums, 0, nums.size() - 1);
}
};