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]

你可能感兴趣的:(LeetCode)