用类似于归并排序的方法解决这道题,把数组分成左右两个数组,然后归并排序,在排序的过程中统计逆序对的个数
class Solution {int[] nums, tmp;public int reversePairs(int[] nums) {this.nums = nums;tmp = new int[nums.length];return mergeSort(0, nums.length-1);}private int mergeSort(int l, int r){//终止条件if(l >= r) return 0;//递归划分int m = (l + r) / 2;int res = mergeSort(l, m) + mergeSort(m+1, r);//合并阶段int i = l, j= m+1;for(int k = l; k<=r; k++){tmp[k] = nums[k];}for(int k = l; k<=r; k++){if(i == m+1){nums[k] = tmp[j++];}else if(j == r+1 || tmp[i] <= tmp[j]){nums[k] = tmp[i++];}else{nums[k] = tmp[j++];res += m - i + 1;//统计逆序对}}return res;}
}