题解 | #数组中的逆序对#
数组中的逆序对
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
public class Solution {
private int re = 0;
public int InversePairs(int [] array) {
merge(array,0,array.length-1);
return re;
}
public void merge(int[] array,int s,int e){
if(s>=e){
return;
}
int c = (s+e)>>1;
merge(array,s,c);
merge(array,c+1,e);
int[] temp = new int[e-s+1];
int i = 0;
int r = c+1;
int t = s;
while(s<=c && r<=e){
if(array[s]<=array[r]){
temp[i++] = array[s++];
}else{
re = (re + c - s + 1)%1000000007;
temp[i++] = array[r++];
}
}
while(s<=c){
temp[i++] = array[s++];
}
while(r<=e){
temp[i++] = array[r++];
}
for (int value : temp) {
array[t++] = value;
}
}
}