-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path493. Reverse Pairs.cpp
77 lines (63 loc) · 1.39 KB
/
493. 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
private:
void merge(vector<int>&a , int s, int mid, int e)
{
int i = s, j = mid + 1;
int n = e - s + 1;
int temp[n];
int k = 0;
while(i<=mid && j<=e)
{
if(a[i] > a[j]){
temp[k++] = a[j];
j++;
}
else{
temp[k++] = a[i];
i++;
}
}
while(i<=mid)
{
temp[k++] = a[i];
i++;
}
while(j <= e){
temp[k++] = a[j];
j++;
}
for(int i=s; i<=e; i++)
{
a[i] = temp[i - s];
}
}
int countPairs(vector<int>&a , int s, int mid, int e)
{
int j = mid + 1;
int cnt = 0;
for(int i=s; i<=mid; i++)
{
while(j<=e && a[i] >(long long)2*a[j])
j++;
cnt += (j - (mid+1));
}
return cnt;
}
int mergeSort(vector<int>&a, int s, int e)
{
int cnt = 0;
if(s >= e){
return cnt;
}
int mid = (s + e)/2;
cnt += mergeSort(a, s, mid);
cnt += mergeSort(a, mid+1, e);
cnt += countPairs(a, s, mid, e);
merge(a, s, mid, e);
return cnt;
}
public:
int reversePairs(vector<int>& nums) {
return mergeSort(nums, 0, nums.size()-1);
}
};