1.题目描述
给定一个整数数组 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 个更小的元素.
2.解题思路
设置一个新数组queue,从后向前遍历原数组,将当前遍历的元素插入到queue中的正确位置,这个位置即为右侧比他小的元素的个数。
bisect是python内置模块,用于有序序列的插入和查找。
- 查找: bisect(array, item)
- 插入: insort(array,item)
bisect还有bisect_left,insort_left的用法,和不带left的用法的区别是:当插入的元素和序列中的某一个元素相同时,该插入到该元素的前面(左边,left),还是后面(右边,right);如果是查找,则返回该元素的位置还是该元素之后的位置。
线段树,以数组的最小值和最大值作作为根节点的左右区间,遍历数组每一个元素num,num在某一区间出现过,则一边建树,一边让count++1,返回的是线段树中比num小的值得数量。
3.代码实现
解法一:
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
import bisect
queue = []
res = []
for num in nums[::-1]:
# 该插入的位置
loc = bisect.bisect_left(queue, num)
res.append(loc)
# 排好序的数组
queue.insert(loc, num)
return res[::-1]
解法二:
class Node():
def __init__(self,begin,end):
self.begin = begin
self.end = end
self.mid = (begin+end)//2
self.count = 0
self.left = None
self.right = None
def add(self,num):
# 返回线段树中比num小的值的数量
self.count += 1
if self.begin == self.end:
return 0
else:
if not self.left:
self.left = Node(self.begin, self.mid)
if not self.right:
self.right = Node(self.mid + 1, self.end)
if num <= self.mid:
return self.left.add(num)
else:
return self.left.count + self.right.add(num)
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
mn = min(nums)
mx = max(nums)
root = Node(mn,mx)
res = []
# 这里倒着计算,返回数组前面比自己小的个数
for i in range(len(nums)-1,-1,-1):
# 一边构建线段树一边计算答案
res.append(root.add(nums[i]))
return res[::-1]