剑指offer—数组中的逆序对

来源:互联网 发布:java 格式化html 编辑:程序博客网 时间:2024/05/17 03:33

题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

public class Solution {    public int InversePairs(int [] array) {        if(array==null || array.length<=0) return 0;        int end = array.length-1;        int[] copy = new int[array.length];        for(int i=0; i<array.length; i++){            copy[i] = array[i];        }        int count = InversePairsCore(array,copy,0,end);        return count;    }    public int InversePairsCore(int[] array, int[] copy,int start, int end){        if(start==end){            return 0;        }        int length = (end-start)/2;        int left = InversePairsCore(copy,array,start,start+length)%1000000007;        int right = InversePairsCore(copy,array,start+length+1,end)%1000000007;        int i=start+length;        int j = end;        int index = end;        int count = 0;        while(i>=start && j>=start+length+1){            if(array[i]>array[j]){                count += (j-start-length);                copy[index--] = array[i--];               if(count>=1000000007)//数值过大求余               {                   count%=1000000007;               }            }else{                copy[index--] = array[j--];            }        }        for(;i>=start;i--){            copy[index--] = array[i];        }        for(; j>=start+length+1; j--){            copy[index--] = array[j];        }        return (count+left+right)%1000000007;    }}

利用归并排序的思想,先将数组分开,在合并,在两个小数组中合并之前,先计算每一个小数组的逆序对的个数,并分别讲每个小数组排序,在合并的过程中,从第一个小数组的最后一个元素出发,算出每个元素可以和后面数组有几个满足逆序对的

原创粉丝点击