You need to return the number of important reverse pairs in the given array.
Input: [1,3,2,3,1]
Output: 2
Input: [2,4,3,5,1]
Output: 3
class Solution {
public int reversePairs(int[] nums) {
return mergeSort(nums, 0, nums.length - 1);
}
public int mergeSort(int[] nums, int start, int end) {
if (start >= end)
return 0;
int mid = start + (end - start) / 2;
int leftAns = mergeSort(nums, start, mid);
int rightAns = mergeSort(nums, mid + 1, end);
return leftAns + rightAns + merge(nums, start, end);
}
public int merge(int[] nums, int start, int end) {
int mid = start + (end - start) / 2;
int p1 = start, p2 = mid + 1;
int pointer = mid + 1, index = 0, count = 0;
int[] temp = new int[end - start + 1];
while (p1 <= mid) {
// All the elements behind pointer, are satisfying the equation with "p1"
while (pointer <= end && 2L * nums[pointer] < (long) nums[p1])
pointer++;
count += pointer - (mid + 1);
while (p2 <= end && nums[p2] < nums[p1])
temp[index++] = nums[p2++];
temp[index++] = nums[p1++];
}
while (p2 <= end)
temp[index++] = nums[p2++];
for (int i = start; i <= end; i++)
nums[i] = temp[i - start];
return count;
}
}