数组中的逆序对

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

数据范围:

对于%50的数据,size<=10^4

对于%75的数据,size<=10^5

对于%100的数据,size<=2*10^5

示例1
输入
1,2,3,4,5,6,7,0
输出
7

int count = 0;
    public int InversePairs(int[] array) {
        if (array == null || array.length == 0) return 0;
        sort(array, new int[array.length], 0, array.length-1);
        return count % 1000000007;
    }
    
    private void sort(int[] a, int[] aux, int lo, int hi) {
        if (lo >= hi) return;
        
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid+1, hi);
        
        merge(a, aux, lo, mid, hi);
    }
    
    private void merge(int[] a, int[] aux, int lo, int mid, int hi) {
        for (int i = lo; i <= hi; i++)
            aux[i] = a[i];
        
        int i = lo, j = mid+1; 
        for (int k = lo; k <= hi; k++) {
            if (i > mid) a[k] = aux[j++];
            else if (j > hi) a[k] = aux[i++];
            else if (aux[i] <= aux[j]) a[k] = aux[i++];
            else {
                a[k] = aux[j++];
                count += mid - i + 1;
                count = count % 1000000007;
            }
        }
    }





int cnt;
    public int InversePairs(int[] array) {

        cnt = 0;
       if (array != null)
           mergerSortUp2Down(array, 0, array.length-1);
       return cnt % 1000000007;
    }

    private void mergerSortUp2Down(int[] a, int lo, int hi) {
        if (lo >= hi) return;
        
        int mid = lo + (hi - lo) / 2;
        
        mergerSortUp2Down(a, lo, mid);
        mergerSortUp2Down(a, mid+1, hi);
        
        merge(a, lo, mid, hi);
    }

    private void merge(int[] a,  int lo, int mid, int hi) {

        int[] tmp = new int[hi - lo + 1];

        int i = lo, j = mid + 1, k = 0;

        while (i <= mid && j <= hi) {

            if (a[i] <= a[j]) {
                tmp[k++] = a[i++];
            }
            else {
                tmp[k++] = a[j++];
                cnt += mid - i + 1;
                cnt %= 1000000007;
            }
        }

        while (i <= mid)
            tmp[k++] = a[i++];

        while (j <= hi)
            tmp[k++] = a[j++];

        for (k = 0; k < tmp.length; k++) {
            a[lo+k] = tmp[k];
        }
    }

你可能感兴趣的:(剑指offer)