Count of Smaller Numbers after self
You were given an integer array nums and you had to return a new counts array. The counts array has the property where are the number of smaller elements to the right of counts[i]
nums[i]
.
Example:
nums = [5, 2, 6, 1]to the right of 5 there is 2 smaller elements (2 and 1). The right of 2 there are only 1 smaller element (1). The right of 6 there is 1 smaller element (1). The right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0]
.
https://leetcode.com/problems/count-of-smaller-numbers-after-self/
The number of numbers that are smaller than the current number in the array, and the complexity is less than O (n^2).
First notice that you should traverse from right to left, record the number of accesses, and turn it into a sub-problem:
How to quickly find out all the smaller numbers in a data structure, and this structure to support O (LOGN) insert operation.
Then think of using binary search tree, all the data of the left subtree is smaller than the current node, this side with the array to implement BST.
The binary finds the inserted position, which exactly also represents a few smaller numbers on the left.
1 /**2 * @param {number[]} nums3 * @return {number[]}4 */5 varCountsmaller =function(nums) {6 varI, BST = [], result =[], index, TT1, TT2;7 for(i = nums.length-1; I >= 0; i--){8index =Getbstindex (BST, Nums[i]);9 Result.unshift (index);TenBst.splice (Index, 0, Nums[i]); One } A returnresult; - - functiongetbstindex (BST, num) { the if(Bst.length = = 0)return0; - vari = 0, j = bst.length-1, middle; - if(Bst[j] < num)returnbst.length; - if(Bst[i] >= num)return0; + while(i + 1 <j) { -Middle = (i + j) >> 1; + if(Bst[middle] <num) Ai = middle + 1; at Else -j =Middle; - } - if(Bst[i] >= num)returni; - returnJ; - } in};
[Leetcode] [JavaScript] Count of Smaller Numbers after self