Count of Smaller Numbers After Self

https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/

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].

Example:

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].

Thoughts

  1. 问比它的数小的个数,可以想到BST中从root到它所有要往左的节点数目和路径上每个节点的左子树数目的和。

  2. 节点中除了存值,还存左子树节点数。每次插入一个新节点到左边时,更新parent的这个值

  3. 问右边比小的个数,那就从右往左建树,树中即所有在它右边的数

  4. 有数重复的情况。因此还要一个dup, 默认应该为1.

Code

Analysis

Errors:

  1. 忘了加当node.val == nums[i]时的smallerCount.

树balance时, 时间复杂度O(NlgN).

Ver.2

Iterative建树

Last updated

Was this helpful?