1297. Count of Smaller Numbers After Self (JavaScript)
题目
描述 You are given an integer array nums and you have to return a new counts array.
The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. 样例 Given nums = [5, 2, 6, 1] To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Return the array [2, 1, 1, 0].
思路
题目的意思是,输入一个整数数组,从左向右开始,计算每一个数右边比这个数小的个数。
第一先想到的肯定是遍历穷举,这样无疑会增加时间复杂度,不可取。
正难则反,如果是从n项的数组最后一项n-1开始算起,结果是0;
计算倒数第二项n-2结果的话,要和n-1比较大小,若N(n-2) >N(n-1),结果是1,反之是0
这里可以发现,如果N(n-2) 和N(n-1)放进数组进行排序的话,那么下标就是输出的结果。
因为数是一项一项添加到以及排序后的数组里面的,那么可以通过二分查找插入排序算法,进行解决,只不过这里是从最后一项开始。
代码
/**
* @param nums: a list of integers
* @return: return a list of integers
*/
const countSmaller = function (nums) {
// write your code here
if (nums.length == 0) {
return [];
}
//存下标的
var arr = new Array(nums.length);
for (var i = nums.length - 2; i >= 0; i--) {
var left = i + 1, right = nums.length - 1;
while (left <= right) {
var middle = parseInt((left + right) / 2);
if (nums[i] > nums[middle]) {
right = middle - 1;
} else {
left = middle + 1;
}
}
arr[i] = nums.length - left;
var temp = nums[i];
for(var j = i; j < right; j++) {
nums[j] = nums[j+1];
}
nums[right] = temp;
}
//最后一个为0
arr[nums.length - 1] = 0;
return arr;
}

浙公网安备 33010602011771号