[LeetCode]315. 计算右侧小于当前元素的个数(Count of Smaller Numbers After Self)

题目描述

给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。

示例:

输入: [5,2,6,1]
输出: [2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1).
2 的右侧仅有 1 个更小的元素 (1).
6 的右侧有 1 个更小的元素 (1).
1 的右侧有 0 个更小的元素.

解题思路

类似于[剑指Offer]数组中的逆序对,但是这里变成了元素级别的逆序对数,考虑归并排序的思想。使用“索引数组”的思想,不直接对数组进行排序,而是对数组的索引执行排序操作,这样能够很好的记录每个元素的逆序对数,写入到结果中去。

代码

Python 3.6

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
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
length = len(nums)
if length == 0:
return []
if length == 1:
return [0]
indices = [i for i in range(length)]
tmp = [None for _ in range(length)]
res = [0 for _ in range(length)]
self.find(nums, 0, length - 1, indices, tmp, res)
return res

def find(self, nums, left, right, indices, tmp, res):
if left == right:
return
mid = (left + right) // 2
self.find(nums, left, mid, indices, tmp, res)
self.find(nums, mid + 1, right, indices, tmp, res)
if nums[indices[mid]] <= nums[indices[mid + 1]]:
return
self.sort(nums, left, mid, right, indices, tmp, res)

def sort(self, nums, left, mid, right, indices, tmp, res):
for i in range(left, right + 1):
tmp[i] = indices[i]
l, r = left, mid + 1
for i in range(left, right + 1):
if l > mid:
indices[i] = tmp[r]
r += 1
elif r > right:
indices[i] = tmp[l]
res[indices[i]] += right - mid
l += 1
elif nums[tmp[l]] <= nums[tmp[r]]:
indices[i] = tmp[l]
res[indices[i]] += r - mid - 1
l += 1
else:
indices[i] = tmp[r]
r += 1

执行用时:196 ms
内存消耗:16.2 MB

参考

https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self/solution/gui-bing-pai-xu-suo-yin-shu-zu-python-dai-ma-java-