星级:2
1.数组中的逆序对
【题目】
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数 P。并将 P 对 1000000007 取模的结果输出。 即输出 P%1000000007
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
【代码】
/**
*在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
* 输入一个数组,求出这个数组中的逆序对的总数 P。
* 并将 P 对 1000000007 取模的结果输出。 即输出 P%1000000007
*
* 利用归并排序的思想(倒序)
* 当得到left和right两个待归并的数组时,由于二者已经排好顺序
* 当left中的A元素大于right中的B元素,
* 那么right.length-b_index 个逆序对
* */
int count;
public int InversePairs(int [] array) {
return Merge(array,0,array.length-1);
}
public int Merge(int[] a, int start, int end) {
if (start >= end) return count;
int i,j,mid,index;
int[] temp;
mid = (start + end) / 2;
Merge(a,start,mid);
Merge(a,mid+1,end);
i = start;
j = mid + 1;
temp = new int[end-start+1];
index = 0;
while (i<=mid && j<=end) {
if (a[i] > a[j]) {
count = (count +end - j + 1) % 1000000007;
temp[index++] = a[i++];
} else {
temp[index++] = a[j++];
}
}
while (i<=mid) temp[index++] = a[i++];
while (j<=end) temp[index++] = a[j++];
index = start;
for (i=0;i<temp.length; i++) {
a[index++] = temp[i];
}
return count;
}
【思考】
在归并排序的过程中 后一个数组的数如小于前一个数组的数,则一定能够构成逆序对且逆序对的数目可计算,因为待