LeetCode315 计算右侧小于当前元素的个数(树状数组)

LeetCode315 计算右侧小于当前元素的个数

离散化+树状数组

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        
        clean = list(set(nums))
        clean.sort()
        n = len(clean)
        bit = [0] * (n + 1)

        def lowbit(x): return x & (-x)

        def add(pos, x):
            if pos < 1: return
            while pos <= n:
                bit[pos] += x
                pos += lowbit(pos)
        
        def query(pos):
            count = 0
            while pos > 0:
                count += bit[pos]
                pos -= lowbit(pos)
            return count
        
        rank, l, ans = {}, len(nums), []
        for i in range(n): rank[clean[i]] = i + 1

        for i in range(l - 1, -1, -1):
            cur = query(rank[nums[i]] - 1)
            ans.append(cur)
            add(rank[nums[i]], 1)
        
        ans.reverse()
        return ans

posted on 2022-07-05 19:44  solvit  阅读(32)  评论(0)    收藏  举报

导航