# 315. Count of Smaller Numbers After Self

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

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

> 内容描述

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

Input: [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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)******

直接sb做法，超时

```
class Solution:
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []
        
        res = [0] * len(nums)
        for i in range(len(nums)-1)[::-1]:
            res[i] = sum(nums[j] < nums[i] for j in range(i+1, len(nums)))

        return res
```


> 思路 2
******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)******

虽然也是O(N^2)的解法，因为insert也是O(N)的，但是快了不少，可以ac

beats 74.73%

```python
class Solution:
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res, seen = [], []
        for num in nums[::-1]:
            idx = bisect.bisect_left(seen, num)
            res.append(idx)
            seen.insert(idx, num)
        
        return res[::-1]
```
























