-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReversepairs.cpp
More file actions
68 lines (55 loc) · 1.21 KB
/
Reversepairs.cpp
File metadata and controls
68 lines (55 loc) · 1.21 KB
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
class Solution {
public:
void merge(vector<int>& nums,int low,int mid,int high,int& count){
vector<int> temp;
int left=low;
int right=mid+1;
while(left<=mid && right<=high){
if((long long)nums[right]*2<nums[left]){
count+=mid-left+1;
right++;
}else{
left++;
}
}
int i=low;
int j=mid+1;
while(i<=mid && j<=high){
if(nums[j]>nums[i]){
temp.push_back(nums[i]);
i++;
}else{
temp.push_back(nums[j]);
j++;
}
}
while(i<=mid){
temp.push_back(nums[i]);
i++;
}
while(j<=high){
temp.push_back(nums[j]);
j++;
}
for(int i=low;i<=high;i++){
nums[i]=temp[i-low];
}
}
void mergesort(vector<int>& nums,int low,int high,int& count){
if(low>=high){
return ;
}
int mid=(low+high)/2;
mergesort(nums,low,mid,count);
mergesort(nums,mid+1,high,count);
merge(nums,low,mid,high,count);
}
int reversePairs(vector<int>& nums) {
int low=0;
int n=nums.size();
int high=n-1;
int count=0;
mergesort(nums,low,high,count);
return count;
}
};