求数组逆序对
左边数和任一右边数组成降序,就是一组逆序对
[3,1,0,4,3,1]
0:(3,1)(3,0)(3,1)
1:(1,0)
2:无
3:(4,3)(3,1)
4:(3,1)
最终有7对。
自己理解后琢磨的方法
public static void main(String[] args) {
int [] arr = new int[]{3,1,0,4,3,1};
System.out.println(minSum(arr));
}
public static int minSum(int[]arr ){
if(arr ==null || arr.length < 2){
return 0;
}
return process(arr,0,arr.length-1);
}
public static int process(int []arr ,int L,int R){
if(L == R){
return 0;
}
int M = L +((R-L)>>1);
return process(arr,L,M)+process(arr,M+1,R)+merge(arr,L,M,R);
}
public static int merge(int [] arr ,int L,int M,int R){
int ans = 0 ;
int c1 = M;
int c2 = R;
while (c1 >= L && c2 > M ){
ans += arr[c1] > arr[c2] ? (c2-M):0;
if (arr[c1] > arr[c2]) {
c1--;
} else {
c2--;
}
}
int[] help = new int[R - L +1];
int i = 0;
int p1 = L;
int p2 = M+1;
while (p1 <= M && p2 <= R){
help[i++]=arr[p1]<=arr[p2]?arr[p1++]:arr[p2++];
}
while (p1 <= M){
help[i++] = arr[p1++];
}
while (p2 <= R){
help[i++] = arr[p2++];
}
for (int j = 0;j<help.length;j++) {
arr[L+j] = help[j];
}
return ans;
}
大神的方法:
public static int reverPairNumber(int[] arr) {
if (arr == null || arr.length < 2) {
return 0;
}
return process(arr, 0, arr.length - 1);
}
// arr[L..R]既要排好序,也要求逆序对数量返回
// 所有merge时,产生的逆序对数量,累加,返回
// 左 排序 merge并产生逆序对数量
// 右 排序 merge并产生逆序对数量
public static int process(int[] arr, int l, int r) {
if (l == r) {
return 0;
}
// l < r
int mid = l + ((r - l) >> 1);
return process(arr, l, mid) + process(arr, mid + 1, r) + merge(arr, l, mid, r);
}
public static int merge(int[] arr, int L, int m, int r) {
int[] help = new int[r - L + 1];
int i = help.length - 1;
int p1 = m;
int p2 = r;
int res = 0;
while (p1 >= L && p2 > m) {
res += arr[p1] > arr[p2] ? (p2 - m) : 0;
help[i--] = arr[p1] > arr[p2] ? arr[p1--] : arr[p2--];
}
while (p1 >= L) {
help[i--] = arr[p1--];
}
while (p2 > m) {
help[i--] = arr[p2--];
}
for (i = 0; i < help.length; i++) {
arr[L + i] = help[i];
}
return res;
}