- 标签:树状数组、线段树、数组、二分查找、分治、有序集合、归并排序
- 难度:困难
题目大意
#
给定一个整数数组 nums
。
要求:返回一个新数组 counts
。其中 counts[i]
的值是 nums[i]
右侧小于 nums[i]
的元素的数量。
解题思路
#
可以用树状数组解决。
首先对数组进行离散化处理。把原始数组中的数据映射到 [0, len(nums) - 1]
这个区间。
- 然后逆序顺序从数组
nums
中遍历元素 nums[i]
。计算其离散化后的排名 index
,查询比 index
小的数有多少个。将其记录到答案数组的对应位置 ans[i]
上。
- 然后在树状数组下标为
index
的位置上,更新值为 1
。
重复上述步骤直到遍历完所有元素。最后输出答案数组即可。
代码
#
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
|
import bisect
class BinaryIndexTree:
def __init__(self, n):
self.size = n
self.tree = [0 for _ in range(n + 1)]
def lowbit(self, index):
return index & (-index)
def update(self, index, delta):
while index <= self.size:
self.tree[index] += delta
index += self.lowbit(index)
def query(self, index):
res = 0
while index > 0:
res += self.tree[index]
index -= self.lowbit(index)
return res
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
size = len(nums)
if size == 0:
return []
if size == 1:
return [0]
# 离散化
sort_nums = list(set(nums))
sort_nums.sort()
size_s = len(sort_nums)
bit = BinaryIndexTree(size_s)
ans = [0 for _ in range(size)]
for i in range(size - 1, -1, -1):
index = bisect.bisect_left(sort_nums, nums[i]) + 1
ans[i] = bit.query(index - 1)
bit.update(index, 1)
return ans
|