[python]leetcode(315). Count of Smaller Numbers After Self

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

还有一种解法是使用二叉树维持存储的数字,思路和之前数组存储的方式差不多,
优点:不用移动数组中的元素
缺点:二叉树可能左右不平衡

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值