-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversePairs.java
More file actions
57 lines (49 loc) · 1.57 KB
/
reversePairs.java
File metadata and controls
57 lines (49 loc) · 1.57 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
class Solution {
// Striver Sheet Explaination Sheet
public int reversePairs(int[] nums) {
return mergeSort(nums, 0, nums.length - 1);
}
private int mergeSort(int[] arr, int low, int high) {
int count = 0;
if (low >= high) {
return count;
}
int mid = low + (high - low) / 2;
count += mergeSort(arr, low, mid);
count += mergeSort(arr, mid + 1, high);
count += countPairs(arr, low, mid, high);
merge(arr, low, mid, high);
return count;
}
private void merge(int[] arr, int low, int mid, int high) {
int[] newArr = new int[high - low + 1];
int left = low, right = mid + 1, index = 0;
while (left <= mid && right <= high) {
if (arr[left] <= arr[right]) {
newArr[index++] = arr[left++];
} else {
newArr[index++] = arr[right++];
}
}
while (left <= mid) {
newArr[index++] = arr[left++];
}
while (right <= high) {
newArr[index++] = arr[right++];
}
for (int i = 0; i < newArr.length; i++) {
arr[low + i] = newArr[i];
}
}
private int countPairs(int[] arr, int low, int mid, int high) {
int count = 0;
int right = mid + 1;
for (int left = low; left <= mid; left++) {
while (right <= high && arr[left] > 2L * arr[right]) {
right++;
}
count += (right - (mid + 1));
}
return count;
}
}