题目
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
题目链接:剑指 Offer 51. 数组中的逆序对
示例 1:
输入: [7,5,6,4]
输出: 5
思路
使用归并排序,重点在于合的过程中,使用两个指针指向数组的末尾,使用一个指针指向临时数组的末尾。如果第一个子数组中的数字大于第二个子数组的数字,那么则构成逆序对,并且逆序对的数目等于等于第二个数组中剩余数字的个数。
代码实现
//时间复杂度0(nlogn),空间复杂度o(n)
public int reversePairs(int[] nums) {
if (nums.length <= 0 || nums == null) {
return 0;
}
int count = getCount(nums, 0, nums.length - 1);
return count;
}
public static int getCount(int[] nums, int start, int end) {
if (start >= end) {
return 0;
}
int mid = start + (end - start) / 2;
//分解
int left = getCount(nums, start, mid);
int right = getCount(nums, mid + 1, end);
//合并
int count = 0;
int i = mid;//左边区域的指针
int j = end;//右边区域的指针
int[] temp = new int[end-start + 1];
int k = end-start;//临时数组的指针
while (i>=start&&j>=mid+1){
if(nums[i]>nums[j]){
count+=(j-mid);
temp[k--]=nums[i--];
}else{
temp[k--]=nums[j--];
}
}
//如果左边区域有剩余部分
while (i>=start){
temp[k--]=nums[i--];
}
//如果右边区域有剩余部分
while (j>=mid+1){
temp[k--]=nums[j--];
}
//将临时数组中元素的拷贝到原来的数组中,注意并不是从头开始拷贝
for (int l = 0; l <temp.length ; l++) {
nums[l+start]=temp[l];
}
return count+left+right;
}