forked from strang3-r/Leetcode75
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount_Reverse_Pairs.java
More file actions
55 lines (48 loc) · 1.55 KB
/
Count_Reverse_Pairs.java
File metadata and controls
55 lines (48 loc) · 1.55 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
//https://leetcode.com/problems/reverse-pairs/
//Given an array of numbers, you need to return the count of reverse pairs. Reverse Pairs are those pairs where i<j and arr[i]>2*arr[j].
// Time Complexity : O( N log N ) + O (N) + O (N)
// Space Complexity : O(N)
import java.util.*;
public class Count_Reverse_Pairs {
static int merge(int[] nums, int low, int mid, int high) {
int cnt = 0;
int j = mid + 1;
for(int i = low;i<=mid;i++) {
while(j<=high && nums[i] > (2 * (long) nums[j])) {
j++;
}
cnt += (j - (mid+1));
}
ArrayList<Integer> temp = new ArrayList<>();
int left = low, right = mid+1;
while(left <= mid && right<=high) {
if(nums[left]<=nums[right]) {
temp.add(nums[left++]);
}
else {
temp.add(nums[right++]);
}
}
while(left<=mid) {
temp.add(nums[left++]);
}
while(right<=high) {
temp.add(nums[right++]);
}
for(int i = low; i<=high;i++) {
nums[i] = temp.get(i - low);
}
return cnt;
}
static int mergeSort(int[] nums, int low, int high) {
if(low>=high) return 0;
int mid = (low + high) / 2;
int inv = mergeSort(nums, low, mid);
inv += mergeSort(nums, mid+1, high);
inv += merge(nums, low, mid, high);
return inv;
}
public int reversePairs(int[] nums) {
return mergeSort(nums, 0, nums.length - 1);
}
}