Leetcode 315. Count of Smaller Numbers After Self

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count of Smaller Numbers After Self

2. Solution

解析:Version 1,从右往左遍历数组,每次都将数据放到有序序列里,使用二分查找寻找数据所在的位置,索引位置即为右侧小于数据的个数。

  • Version 1
1
2
3
4
5
6
7
8
9
10
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * n
order = []
for i in range(n-1, -1, -1):
index = bisect.bisect_left(order, nums[i])
ans[i] = index
order.insert(index, nums[i])
return ans

Reference

  1. https://leetcode.com/problems/count-of-smaller-numbers-after-self/
如果有收获,可以请我喝杯咖啡!