[leetCode]剑指 Offer 51. 数组中的逆序对
解法
可以使用归并排序的方法将数组分解成子数组,将子数组归并排序统计子数组的逆序数,最终统计整个数组的逆序数。
class Solution {
public int reversePairs(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int[] copy = Arrays.copyOf(nums, nums.length);
int count = reversePairsCore( nums, copy, 0, nums.length - 1);
return count;
}
private int reversePairsCore(int[] nums, int[] copy, int start, int end) {
if(start>=end) {
copy[start] = nums[start];
return 0;
}
int mid = start + (end - start)/2;
int count = 0;
int left = reversePairsCore(copy, nums, start, mid);
int right = reversePairsCore(copy, nums, mid+1, end);
int i = mid, j = end;
for(int k = end; k >= start; k--) {
if(j < mid + 1) copy[k] = nums[i--];
else if(i < start) copy[k] = nums[j--];
else if(nums[i] > nums[j]) {
count += j - mid ;
copy[k] = nums[i--];
}else {
copy[k] = nums[j--];
}
}
return left + right + count;
}
}