题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
思路:总体思想是递归+归并。先把数组分隔成子数组,先统计出子数组内部的逆序对的数目,然后再统计出两个相邻子数组之间的你修帝的数目。在统计的过程中,还需要对数组进行排序,这里用归并排序。对于两个数组的比较,我们可以用两个指针分别指向两个子数组的末尾,并每次比较两个指针的指向的数字。如果第一个子数组中的数字大于第二个子数组中的数字,则构成逆序对,并且逆序对的数目等于第二个子数组中剩余数字的个数。如果第一个数组中得数字小于或等于第二个数组中的数字,则不构成逆序对。每一次比较的时候,把较大的数字从后往前复制到一个辅助数组中去,确保辅助数组中的数字是递增排序的。把较大的数字复制到辅助数组中之后,把对应的指针向前移动一位,再进行循环比较。
public static int inversePairs(int[] nums){
if(nums == null || nums.length <= 0){
return 0;
}
int length = nums.length;
int[] copy = new int[length];
for(int i=0;i<length;i++){
copy[i] = nums[i];
}
int count = inversePairsCore(nums,copy,0,length-1);
return count;
}
private static int inversePairsCore(int[] nums,int[] copy,int start,int end){
if(start == end){
copy[start] = nums[start];
return 0;
}
int length = (end-start)/2;
int left = inversePairsCore(copy,nums,start,start+length);
int right = inversePairsCore(copy,nums,start+length+1,end);
int i =start + length;
int j = end;
int indexcopy = end;
int count = 0;
while(i>=start && j>=start+length+1){
if(nums[i]>nums[j]){
copy[indexcopy--] = nums[i--];
count += j-start-length;
}
else{
copy[indexcopy--] = nums[j--];
}
}
for(;i>=start;i--){
copy[indexcopy--] = nums[i];
}
for(;j>=start+length+1;j--){
copy[indexcopy--] = nums[j];
}
return left+right+count;
}