To prove safety: reverse in the array

Title Description

Two numbers in the array, if a number is greater than the front behind the figures, the two numbers form a reverse pair. Enter an array, this array P. finds the total number of reverse pair P and outputs the result modulo 1000000007. I.e., the output P% 1000000007

Enter a description:

Title ensure the same number of the input array is not

data range:

50% of the data, size <= 10 ^ 4

75% of the data, size <= 10 ^ 5

100% of the data, size <= 2 * 10 ^ 5

Example 1

Entry

1,2,3,4,5,6,7,0

Export

7 

Solution:

such as:

 

(A) the length of the array 4 into two sub-arrays of length 2;
(B) the length of the array 2 is decomposed into two sub-arrays of Chengdu 1;
(c) the length of the sub-array 1 is combined sorting and counting reverse order ;
(D) the length of the subarray 2 merge, sorting, and counting on the reverse;
 
import java.util.Arrays;

public class Solution {

     public static int InversePairs(int [] array) {
        if(array==null||array.length==0)
        {
            return 0;
        }
        
//        int[] copy = new int[array.length];
//        for(int i=0;i<array.length;i++)
//        {
//            copy[i] = array[i];
//        }
        int[] copy = Arrays.copyOf(array, array.length);
        int count = InversePairsCore(array,copy,0,array.length-1);//数值过大求余
        return count;   
     }

    private static int InversePairsCore(int[] array, int[] copy, int l, int r) {
        if(l==r){
            return 0;
        }
        int mid = l + ((r-l)>>1);
        int lCount = InversePairsCore(array,copy, l, mid)%1000000007;
        int rCount = InversePairsCore(array,copy, mid+1, r)%1000000007;
        int count = 0;
        int i=mid;
        int j=r;
        int locCopy = r;
        while(i>=l && j>mid){
            if(array[i]>array[j]){
                count += j-mid; //此注意边界
                copy[locCopy--] = array[i--];
                if(count>=1000000007)//数值过大求余
                {
                    count%=1000000007;
                }
            }else{
                copy[locCopy--] = array[j--];
            }
        }
        
        while(i>=l){
            copy[locCopy--] = array[i--];
        }
        while(j>mid){
            copy[locCopy] = array[j--];
        }
        
        for(int s=l; s<=r; s++){
            array[s] = copy[s];
        }
        
        return (lCount+rCount+count)%1000000007;
    }


    public static void main(String[] args) {
        int[] arr = {1,5,0,3,2};
        int res = InversePairs(arr);
        System.out.println(res);
    }
}
 
     

 












Guess you like

Origin www.cnblogs.com/lisen10/p/11324123.html