315. 计算右侧小于当前元素的个数 python

利用二叉搜索树
class Tree:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.num = 1


class Solution:
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        def insert(root, val):
            if root.val < val:
                if root.right is not None:
                    root.right = insert(root.right, val)
                else:
                    root.right = Tree(val)
            else:
                if root.left is not None:
                    root.num += 1
                    root.left = insert(root.left, val)
                else:
                    root.num += 1
                    root.left = Tree(val)
            return root

        n = len(nums)
        if n == 0:
            return []
        root = Tree(nums[-1])
        ret = [0]
        for i in range(n - 2, -1, -1):
            root = insert(root, nums[i])
            cnt = 0
            pointer = root
            while pointer.val != nums[i]:
                if pointer.val > nums[i]:
                    pointer = pointer.left
                else:
                    cnt += pointer.num
                    pointer = pointer.right
            ret.append(cnt)
        return ret[::-1]
在样例出错,主要原因是二叉树中出现相同的数字时候,判别出错
nums = [26,78,27,100,33,67,90,23,66,5,38,7,35,23,52,22,83,51,98,69,81,32,78,28,94,13,2,97,3,76,99,51,9,21,84,66,65,36,100,41]
改进之后,代码
class Tree:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.num = 1


class Solution:
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        def insert(root, val, temp):
            if root.val < val:
                temp += root.num
                if root.right is not None:
                    root.right, temp = insert(root.right, val, temp)
                else:
                    root.right = Tree(val)
            else:
                root.num += 1
                if root.left is not None:
                    root.left, temp = insert(root.left, val, temp)
                else:
                    root.left = Tree(val)
            return root, temp

        n = len(nums)
        if n == 0:
            return []
        root = Tree(nums[-1])
        ret = [0]
        for i in range(n - 2, -1, -1):
            root, num = insert(root, nums[i], 0)
            ret.append(num)
        return ret[::-1]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值