题解 | #数组中的逆序对#
数组中的逆序对
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5
归并排序!这个一定要会啊
function InversePairs(data)
{
let sum = 0;
mergeSort(data);
return sum % 1000000007;
# function mergeSort(nums){
if(nums.length < 2) return nums;
// 不断的划分过程,包括一边可能有空的情况
let mid = Math.floor(nums.length / 2)
let left = nums.slice(0,mid);
let right = nums.slice(mid);
return merge(mergeSort(left),mergeSort(right));
}
function merge(left,right){
let res = [];
let leftlen = left.length;
let rightlen = right.length;
let len = leftlen + rightlen;
for(let index = 0,i = 0,j =0;index < len;index ++){
if(i>=leftlen) res[index] = right[j++];
else if(j>=rightlen) res[index] = left[i++];
else if(left[i]<=right[j]) res[index] = left[i++];
else{
// 只有当大于的时候才计数
res[index] = right[j++];
sum += leftlen - i;
sum = sum % 1000000007;
}
}
//console.log(res)
return res;
}
}
module.exports = {
InversePairs : InversePairs
};