<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,2,6,1]
<strong>Output:</strong> [2,1,1,0]
<strong>Explanation:</strong>
To the right of 5 there are <b>2</b> smaller elements (2 and 1).
To the right of 2 there is only <b>1</b> smaller element (1).
To the right of 6 there is <b>1</b> smaller element (1).
To the right of 1 there is <b>0</b> smaller element.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1]
<strong>Output:</strong> [0]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [-1,-1]
<strong>Output:</strong> [0,0]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</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>

class Solution:
    class Pair:
        def __init__(self, val, id):
            # 记录数组的元素值
            self.val = val
            # 记录元素在数组中的原始索引
            self.id = id

    # 归并排序所用的辅助数组
    temp = []
    # 记录每个元素后面比自己小的元素个数
    count = []

    # 主函数
    def countSmaller(self, nums):
        n = len(nums)
        self.count = [0] * n
        self.temp = [self.Pair(0, 0)] * n
        arr = []
        # 记录元素原始的索引位置，以便在 count 数组中更新结果
        for i in range(n):
            arr.append(self.Pair(nums[i], i))

        # 执行归并排序，本题结果被记录在 count 数组中
        self.sort(arr, 0, n - 1)

        res = []
        for c in self.count:
            res.append(c)
        return res

    # 归并排序
    def sort(self, arr, lo, hi):
        if lo == hi:
            return
        mid = lo + (hi - lo) // 2
        self.sort(arr, lo, mid)
        self.sort(arr, mid + 1, hi)
        self.merge(arr, lo, mid, hi)

    # 合并两个有序数组
    def merge(self, arr, lo, mid, hi):
        for i in range(lo, hi + 1):
            self.temp[i] = arr[i]

        i, j = lo, mid + 1
        for p in range(lo, hi + 1):
            if i == mid + 1:
                arr[p] = self.temp[j]
                j += 1
            elif j == hi + 1:
                arr[p] = self.temp[i]
                i += 1
                # 更新 count 数组
                self.count[arr[p].id] += j - mid - 1
            elif self.temp[i].val > self.temp[j].val:
                arr[p] = self.temp[j]
                j += 1
            else:
                arr[p] = self.temp[i]
                i += 1
                # 更新 count 数组
                self.count[arr[p].id] += j - mid - 1
2422