[Leetcode] [JavaScript] Count of Smaller Numbers after self

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.