数组中的逆序对
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
思路
使用归并排序
归并的思想:把数据分成前后两个数组(递归分到每个数组仅有一个数据项),合并数组。
合并时,出现前面的数组值array[i]大于后面数组值array[j]时,则前面数组array[i]~array[mid]都是大于array[j]的,count += mid+1 - i (核心思想)
由于测试用例输出结果比较大,对每次返回的count mod (1000000007)求余
public class Solution {
static int count = 0;
public int InversePairs(int [] array) {
if (array == null || array.length < 2) {
return 0;
}
int[] temp = new int[array.length];
mergesort(array, 0, array.length - 1,temp);
//return count % 1000000007;
return count;
}
public static void mergesort(int[] a, int first, int last, int[] temp) {
if (first < last) {
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左边有序
mergesort(a, mid + 1, last, temp);// 右边有序
mergearray(a, first, mid, last, temp); //再将二个有序数列合并
}
}
public static void mergearray(int[] a, int first, int mid, int last, int temp[]) {
int f = first, j = mid + 1;
int m = mid, l = last;
int k = 0;
while (f <= m && j <= l) {
if (a[f] <= a[j])
temp[k++] = a[f++];
else{
temp[k++] = a[j++];
count += m - f + 1;//核心代码
count = count % 1000000007;
}
}
while (f <= m)
temp[k++] = a[f++];
while (j <= l)
temp[k++] = a[j++];
for (f = 0; f < k; f++)
a[first + f] = temp[f];
}
}
归并排序通用模板!!!
public static void mergesort(int[] a, int first, int last, int[] temp) {
if (first < last) {
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左边有序
mergesort(a, mid + 1, last, temp);// 右边有序
mergearray(a, first, mid, last, temp); //再将二个有序数列合并
}
}
public static void mergearray(int[] a, int first, int mid, int last, int temp[]) {
int f = first, j = mid + 1;
int m = mid, l = last;
int k = 0;
while (f <= m && j <= l) {
if (a[f] <= a[j])
temp[k++] = a[f++];
else
temp[k++] = a[j++];
}
while (f <= m)
temp[k++] = a[f++];
while (j <= l)
temp[k++] = a[j++];
for (f = 0; f < k; f++)
a[first + f] = temp[f];
}