剑指offer 51
完全就是归并排序分治思想的体现,在合并过程中,计算逆序对
public class Solution {
int[] temp;
public int reversePairs(int[] nums) {
temp = new int[nums.length];
return mergesort(0, nums.length - 1, nums);
}
private int mergesort(int left, int right, int[] nums){
if(left >= right) return 0;
int mid = (left + right) >>> 1;
int leftcnt = mergesort(left, mid, nums);
int rightcnt = mergesort(mid + 1, right, nums);
if(nums[mid] <= nums[mid + 1]){
return leftcnt + rightcnt;
}
int mergecnt = merge_count(left, mid, right, nums);
return mergecnt + leftcnt + rightcnt;
}
private int merge_count(int left, int mid, int right, int[] nums){
for (int i = left; i <= right; i++) {
temp[i] = nums[i];
}
int i = left, j = mid + 1;
int cnt = 0;
for(int k = left; k <= right; k++){
// 这是前面一半已经满了,直接把后面的merge到数组中
if(i == mid + 1) nums[k] = temp[j++];
else if (j == right + 1) nums[k] = temp[i++];
else if (temp[i] <= temp[j]) nums[k] = temp[i++];
else {
nums[k] = temp[j++];
cnt += (mid - i + 1);
}
}
return cnt;
}
}