题解 | #数组中的逆序对#
数组中的逆序对
https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
public class Solution {
public int InversePairs(int [] array) {
int len = array.length;
int start = 0 ;
int end = len - 1;
int []copy = new int[len];
for (int i = 0 ; i < len ; i++) {
copy[i] = array[i];
}
Long count = merge1(array, copy, start, end);
return (int)(count%1000000007L);
}
public Long merge1(int []array, int []copy, int start, int end) {
if (start == end) { //已经为最小分组
copy[start] = array[start];
return 0L;
}
int mid = start + ((end - start) >> 1);
Long left = merge1(copy, array, start, mid);
Long right = merge1(copy, array, mid + 1, end);
int count = 0;
int i = mid;
int j = end;
int copyend = end;
while (i >= start && j >= mid + 1) {
if (array[i] > array[j]) {
copy[copyend--] = array[i--];
count += j - mid;
} else {
copy[copyend--] = array[j--];
}
}
for (; i >= start; i--) {
copy[copyend--] = array[i];
}
for (; j >= mid + 1; j--) {
copy[copyend--] = array[j];
}
return left + right + count;
}
}

腾讯云智研发成长空间 5084人发布