题目:
思路:
题目告诉数据范围明显说明暴力法是A不过这道题的,所以采用归并排序的做法来做。
归并排序的做法这里不赘述了,不会的自行去复习。
归并的同时计算逆序对数
这里注意一点!!归并的过程用for是超时的,要用while的做法
代码:
public class Solution {
public int count = 0;
public int InversePairs(int [] array) {
if (array == null || array.length == 0){
return 0;
}
sort(array, 0, array.length-1);
return count;
}
public void sort(int[] array, int lo, int hi){
if (hi <= lo){
return;
}
int mid = (lo + hi) / 2;
sort(array, lo, mid);
sort(array, mid + 1, hi);
merge(array, lo, mid, hi);
}
public void merge(int[] array, int lo, int mid, int hi){
int i = lo, j = mid + 1;
int[] aux = new int[hi - lo + 1];
int k = 0;
while (i <= mid && j<= hi){
if (array[j] < array[i]){
count += mid-i+1;
count %= 1000000007;
aux[k++] = array[j++];
}else {
aux[k++] = array[i++];
}
}
while (i <= mid){
aux[k++] = array[i++];
}
while (j <= hi){
aux[k++] = array[j++];
}
for (int index = 0; index < aux.length; index++){
array[lo+index] = aux[index];
}
}
}
附上归并排序中归并过程的for写法
public void merge2(int[] array, int lo, int mid, int hi){
int i = lo, j = mid + 1;
int[] aux = new int[hi+1];
for (int k = lo; k <= hi; k++){
//复制出来
aux[k] = array[k];
}
for (int k = lo; k <= hi; k++){
if (i > mid){
array[k] = aux[j++];
}else if (j > hi){
array[k] = aux[i++];
}else if (aux[j] < aux[i]){
array[k] = aux[j++];
}else {
array[k] = aux[i++];
}
}
}