-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJava.java
54 lines (44 loc) · 1.48 KB
/
Java.java
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
class Solution {
public int reversePairs(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
return mergeSortAndCount(nums, 0, nums.length - 1);
}
private int mergeSortAndCount(int[] nums, int start, int end) {
if (start >= end) {
return 0;
}
int mid = (start + end) / 2;
int count = mergeSortAndCount(nums, start, mid) + mergeSortAndCount(nums, mid + 1, end);
// Count reverse pairs
int j = mid + 1;
for (int i = start; i <= mid; i++) {
while (j <= end && nums[i] > 2L * nums[j]) {
j++;
}
count += (j - (mid + 1)); // Count the number of valid j's
}
// Merge the two halves
int[] temp = new int[end - start + 1];
int left = start, right = mid + 1, k = 0;
while (left <= mid && right <= end) {
if (nums[left] <= nums[right]) {
temp[k++] = nums[left++];
} else {
temp[k++] = nums[right++];
}
}
while (left <= mid) {
temp[k++] = nums[left++];
}
while (right <= end) {
temp[k++] = nums[right++];
}
// Copy sorted elements back to the original array
for (int i = 0; i < temp.length; i++) {
nums[start + i] = temp[i];
}
return count;
}
}