方法一:直接两个for循环解决问题,时间复杂度为O(n^2),在一些编程网站上是不能通过的,如力扣、牛客网上剑指offer上的编程题。
方法二:采用分治思想,类似于归并排序,归并排序的实现请参考归并排序
AC代码如下:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {7,5,6,4};
int[] temp = new int[a.length];
System.out.println(reversePairs(0,a.length-1,a,temp));//结果 5,即数组a有5对逆序对
System.out.println(Arrays.toString(a));//结果 [4,5,6,7]
}
private static int reversePairs(int low, int high, int[] a, int[] temp) {
if(low==high) return 0;
int mid = (low+high)>>1;
int leftCount = reversePairs(low,mid,a,temp);
int rightCount = reversePairs(mid+1,high,a,temp);
if(a[mid]<=a[mid+1]) return leftCount +rightCount ;
int ct = 0,i = mid,j = high,idx=high;
while(i>=low&&j>mid){
if(a[i]>a[j]){
ct +=j-mid;
temp[idx--] = a[i--];
}else{
temp[idx--] = a[j--];
}
}
while (i>=low) temp[idx--] = a[i--];
while (j>mid) temp[idx--] = a[j--];
for(i+=1;i<=high;i++) a[i] = temp[i];
return leftCount +rightCount +ct;
}
}