leetcode 剑指 Offer 51. 数组中的逆序对
问题描述: 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
思路: 采用分治的思想,借用归并排序的方式。
/**
* @param {number[]} nums
* @return {number}
*/
var reversePairs = function(nums) {
return calcCount(nums,0,nums.length-1)
};
function calcCount(num,l,r){
if(l>=r)return 0;
let mid=Math.floor((r+l)/2);
let p1=l,p2=mid+1,k=0;
let temp=new Array(r-l+1).fill(0);
let count=0;
count+=calcCount(num,l,mid)
count+=calcCount(num,mid+1,r)
while((p1<=mid)||(p2<=r)){
if((p2>r)||(p1<=mid&&num[p1]<=num[p2])){
temp[k++]=num[p1++]
}else{
temp[k++]=num[p2++];
count+=(mid-p1+1)
}
}
for(let i=l;i<=r;i++){
num[i]=temp[i-l]
}
return count;
}