forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Pairs.cpp
51 lines (46 loc) · 1.15 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
class Solution {
public:
int ans;
int arr[50005]; // Auxiliary array to store number during merging
void msort(vector<int>& nums, int st, int ed){
if (ed-st<2) return;
int mid=st+(ed-st)/2;
msort(nums, st, mid);
msort(nums, mid, ed);
int i=st, j=mid, k=0;
int a=st, b=mid;
// two pointer to count "Important pairs"
while (a<mid && b<ed){
if (nums[a]>2ll*nums[b]){
ans+=(mid-a);
b++;
}
else{
a++;
}
}
// normal merge of two sorted arrays
while (i<mid && j<ed){
if (nums[i]<nums[j]){
arr[k++]=nums[i++];
}
else{
arr[k++]=nums[j++];
}
}
while (i<mid){
arr[k++]=nums[i++];
}
k--;
while(k>-1){
nums[st+k]=arr[k];
k--;
}
return ;
}
int reversePairs(vector<int>& nums) {
ans=0;
msort(nums, 0, nums.size());
return ans;
}
};