problem
You are given an integer array nums and you have to return a new
counts array. The counts array has the property where counts[i] is the
number of smaller elements to the right of nums[i].Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1). To the right
of 2 there is only 1 smaller element (1). To the right of 6 there is 1
smaller element (1). To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
分析
最朴素的想法就是从左向右对每一个元素都检查右边有几个元素比它小,这样的时间复杂度是
O(n2)
,其实这个问题可以分解为子问题来求解,即每一个元素对应的count都等于它右边的、比它小的数字中的最大的那个的count加一,
f(i)=1+f(j),j=argmaxnums[j],j>i and nums[j]<nums[i]
。
那么关键就在于怎么快速的找到那个比num[i]小的元素中最大的那个?可以使用一个数组维持已遍历的元素,然后使用二分查找找到相应的元素并把当前元素加入。
#超过了90%
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
import bisect
n = len(nums)
ans = [None]*n
tmp = []
for i in range(n-1, -1, -1):
t = nums[i]
pos = bisect.bisect_left(tmp, t)
ans[i] = pos
tmp.insert(pos, t)
return ans
还有一种解法是使用二叉树维持存储的数字,思路和之前数组存储的方式差不多,
优点:不用移动数组中的元素
缺点:二叉树可能左右不平衡