solution.md 2.5 KB
Newer Older
ToTensor's avatar
ToTensor 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
# 计算右侧小于当前元素的个数

<p>给你`一个整数数组 <code>nums</code><em> </em>,按要求返回一个新数组&nbsp;<code>counts</code><em> </em>。数组 <code>counts</code> 有该性质: <code>counts[i]</code> 的值是&nbsp; <code>nums[i]</code> 右侧小于&nbsp;<code>nums[i]</code> 的元素的数量。</p>

<p>&nbsp;</p>

<p><strong>示例 1:</strong></p>

<pre>
<strong>输入:</strong>nums = [5,2,6,1]
<strong>输出:</strong><code>[2,1,1,0] 
<strong>解释:</strong></code>
5 的右侧有 <strong>2 </strong>个更小的元素 (2 和 1)
2 的右侧仅有 <strong>1 </strong>个更小的元素 (1)
6 的右侧有 <strong>1 </strong>个更小的元素 (1)
1 的右侧有 <strong>0 </strong>个更小的元素
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>输入:</strong>nums = [-1]
<strong>输出:</strong>[0]
</pre>

<p><strong>示例 3:</strong></p>

<pre>
<strong>输入:</strong>nums = [-1,-1]
<strong>输出:</strong>[0,0]
</pre>

<p>&nbsp;</p>

<p><strong>提示:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>


## template

```python
class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        n = len(nums)
        if n == 0:
            return []

        numsarr = [[nums[i], i] for i in range(n)]

        res = [0 for _ in range(n)]

        def merge(left, right):

            if left == right:
                pass
            else:

                mid = left + (right - left) // 2

                merge(left, mid)
                merge(mid + 1, right)

                temp = []

                i = left
                j = mid + 1

                while i <= mid and j <= right:

                    if numsarr[i][0] <= numsarr[j][0]:
                        temp.append(numsarr[j])
                        j += 1

                    else:
                        temp.append(numsarr[i])
                        res[numsarr[i][1]] += right - j + 1
                        i += 1

                while i <= mid:
                    temp.append(numsarr[i])
                    i += 1
                while j <= right:
                    temp.append(numsarr[j])
                    j += 1

                numsarr[left : right + 1] = temp[:]

        merge(0, n - 1)
        return res



```

## 答案

```python

```

## 选项

### A

```python

```

### B

```python

```

### C

```python

```