35. Reverse Pairs in Arrays

Topic description

         Two numbers in an array, if the former number is greater than the latter number, the two numbers form an inverse pair;

         Input an array, find the total number P of inverse pairs in this array. And output the result of P modulo 1000000007. That is, output P%1000000007;

Enter description:

         The question guarantees the same numbers that are not in the input array

         Data range: for %50 data, size<=10^4, for %75 data, size<=10^5, for %100 data, size<=2*10^5

Example 1

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

Problem solving ideas

package page02;

import java.util.Arrays;

public class Solution35 {

    public int InversePairs(int[] array) {
        if (array == null || array.length == 0) {
            return 0;
        }

        int[] copy = Arrays.copyOf(array,array.length);  //复制

        return InversePairsCore(array, copy, 0, array.length - 1);

    }

    private int InversePairsCore(int[] array, int[] copy, int low, int high) {
        if (low == high) {
            return 0; //recursion end condition
        }

        int mid = (low + high) >> 1;

        int leftCount = InversePairsCore(array, copy, low, mid) % 1000000007; //The value is too large and the remainder
        int rightCount = InversePairsCore(array, copy, mid + 1, high) % 1000000007;


        int count = 0; //final result

        int i = mid;
        int j = high;
        int locCopy = high;

        while (i >= low && j > mid) {
            if (array[i] > array[j]) {
                count += j - mid;
                copy[locCopy--] = array[i--];
                
                if (count >= 1000000007){
                    //value is too large
                    count %= 1000000007;
                }
            } else {
                copy[locCopy--] = array[j--];
            }
        }

        for (; i >= low; i--) {
            copy[locCopy--] = array[i];
        }

        for (; j > mid; j--) {
            copy[locCopy--] = array[j];
        }

        for (int s = low; s <= high; s++) {
            array[s] = copy[s];
        }

        return (leftCount + rightCount + count) % 1000000007;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868391&siteId=291194637