java 归并排序求逆序数,先解决相邻数字之间的逆序,再回溯
class Solution {
public int ans = 0;
public int inversePairs(int[] nums) {
int n = nums.length;
int[] helper = new int[n];
merge(nums, helper, 0, n - 1);
return ans;
}
private void merge(int[] nums, int[] helper, int left, int right)
{
if (left >= right)
return;
int mid = left + (right - left) / 2;
merge(nums, helper, left, mid);
merge(nums, helper, mid + 1, right);
for(int i = left ; i <= right; i++)
{
helper[i] = nums[i];
}
int beginLeft = left;
int beginRight = mid + 1;
int current = left;
while(beginLeft <= mid && beginRight <= right)
{
if(helper[beginLeft] <= helper[beginRight])
{
nums[current] = helper[beginLeft];
beginLeft ++;
current++;
}else{
nums[current] = helper[beginRight];
beginRight++;
ans += (mid - beginLeft +1);
current++;
}
}
while(beginLeft <= mid)
{
nums[current] = helper[beginLeft];
beginLeft ++;
current++;
}
while(beginRight <= right)
{
nums[current] = helper[beginRight];
beginRight ++;
current++;
}
}
}