逆序对总数
本文最后更新于:7 个月前
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
/**
* @param {number[]} nums
* @return {number}
*/
const reversePairs = function (nums) {
let count = 0;
const merge = (left, right) => {
let res = [];
while (left.length && right.length) {
if (left[0] > right[0]) {
res.push(left.shift());
count += right.length;
} else {
res.push(right.shift());
}
}
return res.concat(left).concat(right);
};
const split = (nums) => {
if (nums.length <= 1) return nums;
let mid = (nums.length / 2) >> 0;
let left = nums.slice(0, mid),
right = nums.slice(mid);
return merge(split(left), split(right));
};
split(nums);
return count;
};
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!