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

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


public class Solution {
    public int InversePairs(int [] array) {
        int[] copy = new int[array.length];
        for(int i=0;i<array.length;i++){
            copy[i]=array[i];
        }
        return InversePairsCore(array,copy,0,array.length-1);
    }
    
    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);
        int right = InversePairsCore(copy,array,start+length+1,end);
        
        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]){
                copy[index--]=array[i--];
                count+=j-start-length;
                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 (left+count+right)%1000000007;
    }
}



copy和array数组交替排序。
最底层(单个情况)的上一层(2个元素),假设array为指向数组,copy为复制的排序数组,根据array排序好copy





return到上一层。在这一层,刚才的copy是这一层的指向数组,array是这一层的排序数组






这样,array中的元素变成了排序好的,再return上一层,交替之。




猜你喜欢

转载自blog.csdn.net/u010873775/article/details/78860223