数组中的逆序对 --剑指offer

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
 
归并排序的改进 在合并的时候进行计算count的值
先贴上归并排序的代码
public class Solution {
    public static void mergeSort(int [] array) {
        int[] temp=new int[array.length];
        sort(array,temp,0,array.length-1);
    }
    public  static void sort(int[] arr,int[] temp,int left,int right){

        if(left == right){
            return;
        }
        int mid = (left+right)/2;
        sort(arr,temp,left,mid);
        sort(arr,temp,mid+1,right);
        int t=0;
        int i=left,j=mid+1;
        while (i <= mid &&  j<=right)
        {
            if(arr[i]<arr[j]){
                temp[t ++] = arr[i++];
            }
            else {
                temp[t ++] = arr[j++];
            }
        }
        while (i <= mid){
            temp[t ++] = arr[i++];
        }
        while (j <= right){
            temp[t ++] = arr[j++];
        }
        t=0;
        for(i =left;i <= right;i ++){
            arr[i] = temp[t++];
        }
    }
}

本题的代码:

public class Solution {
    public int InversePairs(int [] array) {
        if(array == null || array.length == 0 ){
            return  0;
        }
        int[] temp=new int[array.length];
        return  (sort(array,temp,0,array.length-1))%1000000007;
    }
    public  int sort(int[] arr,int[] temp,int left,int right){

        if(left == right){
            return 0;
        }
        int mid = (left+right)/2;
        int leftcount=sort(arr,temp,left,mid)%1000000007;
        int rightcount=sort(arr,temp,mid+1,right)%1000000007;
        //归并部分
        int i=mid,j=right;
        int count=0;
        int t=right;
        while (i >= left &&  j>=mid+1)
        {
            if(arr[i]>arr[j]){
                temp[t--] = arr[i--];
                count += j-mid;
                if(count > 1000000007){
                    count = count%1000000007;
                }
            }
            else {
                temp[t--]=arr[j--];
            }
        }
        while (i >= left){
            temp[t --] = arr[i--];
        }
        while (j >= mid+1){
            temp[t --] = arr[j--];
        }
        for(i =left;i <= right;i ++){
            arr[i] = temp[i];
        }
        return  (leftcount +rightcount + count)%1000000007;
    }
}

 

posted @ 2020-03-08 15:46  nlw  阅读(133)  评论(0编辑  收藏  举报