-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse-pair.cpp
59 lines (48 loc) · 1.37 KB
/
reverse-pair.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
class Solution {
public:
int reversePairs(vector<int>& nums) {
return mergeSort(nums, 0, nums.size() - 1);
}
private:
int mergeSort(vector<int>& nums, int pre, int next) {
if (pre >= next) {
return 0;
}
int flag = pre + (next - pre) / 2;
int count = mergeSort(nums, pre, flag) + mergeSort(nums, flag + 1, next);
int i = pre;
int j = flag + 1;
while (i <= flag && j <= next) {
if ((long long)nums[i] > 2LL * nums[j]) {
count += flag - i + 1;
j++;
} else {
i++;
}
}
merge(nums, pre, flag, next);
return count;
}
void merge(vector<int>& nums, int pre, int flag, int next) {
vector<int> a(next - pre + 1);
int i = pre;
int j = flag + 1;
int k = 0;
while (i <= flag && j <= next) {
if (nums[i] <= nums[j]) {
a[k++] = nums[i++];
} else {
a[k++] = nums[j++];
}
}
while (i <= flag) {
a[k++] = nums[i++];
}
while (j <= next) {
a[k++] = nums[j++];
}
for (int p = 0; p < a.size(); p++) {
nums[pre + p] = a[p];
}
}
};