题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
运行时间:491ms
占用内存:51228k
注释掉后面一个复制,迷惑
运行时间:508ms
占用内存:54004k
public class Solution {
public int InversePairs(int [] array) {
if(array == null || array.length < 2)
return 0;
int[] copy = new int[array.length];
for(int i=0; i<array.length; i++)
copy[i] = array[i];
return mergeCount(array, copy, 0, array.length-1);
}
private int mergeCount(int[] array, int[] copy, int low, int high){
if(low == high)//数组中只有一个元素当然没有逆序对了
return 0;
//这样计算Mid值是防止high+low的值过大
int mid = low + (high-low)/2;
//int mid = (low+high)>>1;
//分成左右两组,分别计算组内的逆序对数
//同时将array中已计算逆序对数的部分排好序,防止后面在合并时重复统计
int leftcount = mergeCount(array, copy, low, mid);
int rightcount = mergeCount(array, copy, mid+1, high);
//下面将分组统计好的两部分进行统计并合并
int count = 0;
//定义两个指针分别指向每组未进行归并的最大值
int i = mid;
int j = high;
//定义一个指针指向两组中更大的值该存放的位置
int pcopy = high;
while(i>=low && j>mid){
if(array[i]>array[j]){
//array[i]一定也大于array[j]前面的值,因为这些值均小于array[j]
//统计
count += (j-mid);
if(count>=1000000007)//数值过大求余
{
count%=1000000007;
}
//排序
copy[pcopy--] = array[i--];
}
else{
copy[pcopy--] = array[j--];
}
}
while(j > mid)
copy[pcopy--] = array[j--];
//while(i >= low)
//copy[pcopy--] = array[i--];
for(int s=low;s<=high;s++){
array[s] = copy[s];
}
return (leftcount+rightcount+count)%1000000007;
}
}