题解 | #NC118 数组中的逆序对 Java版
数组中的逆序对
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
NC118 数组中的逆序对 Java版
- 暴利破解肯定超时
- 本题考查的是排序 直接归并最省时间 话不多说直接上代码
public class Solution {
static int mod = (int) 1e9 + 7;
static 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 static int[] sort(int[] a,int low,int high){
int mid = (low+high)/2;
if(low<high){
sort(a,low,mid);//分成两个子序列,分别递归排序
sort(a,mid+1,high);
//左右归并
merge(a,low,mid,high);
}
return a;
}
//将两个有序表合并成一个有序表
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high-low+1];//定义一个数组
int i= low;
int j = mid+1;
int k=0;
// 把较小的数先移到新数组中
while(i<=mid && j<=high){
if(a[i]<a[j]){
temp[k++] = a[i++];
}else{
count = (count + mid - i + 1) % mod;
temp[k++] = a[j++];
}
}
// 把左边剩余的数移入数组
while(i<=mid){
temp[k++] = a[i++];
}
// 把右边边剩余的数移入数组
while(j<=high){
temp[k++] = a[j++];
}
// 把新数组中的数覆盖nums数组
for(int x=0;x<temp.length;x++){
a[x+low] = temp[x];//原数组从low开始的
}
}
}