35、数组中的逆序对

一、题目

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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

二、解法

 1 public class Solution {
 2     public int InversePairs(int [] array) {
 3         if(array.length == 0 || array == null)
 4             return 0;
 5         int count = InversePairsCore(array,0,array.length-1);
 6         return count;
 7     }
 8     //用归并排序思想
 9     private int InversePairsCore(int [] array,int low, int high){
10         if(low < high){
11             int mid = (low+high)/2;
12             int leftCount = InversePairsCore(array,low, mid)%1000000007;
13             int rightCount = InversePairsCore(array,mid+1,high)%1000000007;
14             int count = 0;//计算数目
15             int i = mid;//左边部分
16             int j = high;//右边部分
17             int k = high-low;//辅助数组
18             int[] temp = new int[high-low+1];
19             //左右两部分都是从后往前计算
20             while(i>=low && j>mid){
21                 if(array[i] > array[j]){
22                     count += j-mid;
23                     temp[k--] = array[i--];
24                     if(count >= 1000000007)
25                         count %= 1000000007;
26                 }else{
27                     temp[k--] = array[j--];
28                 }
29             }
30             //添加剩下的前半部分到temp中
31             for(;i>=low;i--)
32                 temp[k--] = array[i];
33             //添加剩下的后半部分到temp中
34             for(;j>mid;j--)
35                 temp[k--] = array[j];
36             //将排好序的temp复制到array中
37             for(int v = 0; v < (high-low+1); v++)
38                 array[low+v] = temp[v];
39             return (leftCount+rightCount+count)%1000000007;
40         }
41         return 0;
42     }
43 }
原文地址:https://www.cnblogs.com/fankongkong/p/7456603.html