Count of Smaller Numbers After Self

Jul 8, 2021

Leetcodearrow-up-right

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 1:

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
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.

Example 2:

Input: nums = [-1]
Output: [0]

Example 3:

Input: nums = [-1,-1]
Output: [0,0]

Constraints:

  • 1 <= nums.length <= 10^5

  • -10^4 <= nums[i] <= 10^4

Merge Sort 解法:

在sort的过程中,每次当我们merge两个part的时候,我们可以记录下对于每个数字,有几个数字差到了他的前面,这样当我们最终完成排序的时候,就可以得到结果。

Java Code:

Segment Tree 解法:

我们可以用一个array来存每个值出现过的次数,这样如果想知道小于某个数字的有多少个,可以利用线段树来维持这个array的sum,对于一个数字num,我们只需要query [-inf, num-1] 有多少个即可。

接下来有三个细节需要注意:

  1. 其一是原始数据范围是[-10000,10000] ,而线段树需要从0开始,对此我们可以使用一个OFFSET来解决,给所有num都加上OFFSET。

  2. 其二就是题目要求的是每个数字右边比他小的,而不是全局的,对此我们可以利用线段树logN update的性质,从右往左边update边query,这样每次query到的比当前num小的数字就都是它右边的了。

  3. 最后就是在update的时候我们不是直接替换,因为有可能有重复数字。例如原本有两个 3,又来了一个3,update的时候需要变成4。

Java Code:

Last updated