Python | Leetcode Python题解之第315题计算右侧小于当前元素的个数

题目:

题解:

python 复制代码
import numpy as np
from bisect import bisect_left

class Solution:
    max_len =  10000
    c = []
    buckets = []

    def countSmaller(self, nums: List[int]) -> List[int]:
        self.c = [0 for _ in range(len(nums) + 5)]
        counts = [0 for _ in range(len(nums))]
        nums = self.discretization(nums)
        for i in range(len(nums) - 1, -1, -1):
            num = nums[i]
            counts[i] = self.query(num-1)
            self.updateC(num)
        return counts

    def updateC(self, pos):
        while pos < len(self.c):
            self.c[pos] += 1
            pos += self.lowbit(pos)

    def lowbit(self, x):
        """获取更新范围"""
        return x & (-x)

    def query(self, pos):
        """查询前缀和"""
        val = 0
        while pos > 0:
            val += self.c[pos]
            pos -= self.lowbit(pos)
        return val

    def getMappingList(self, nums):
        """列表去重排序"""
        return list(sorted(set(nums)))

    def discretization(self, nums):
        """将nums进行离散化变换"""
        mapping = self.getMappingList(nums)
        return [bisect_left(mapping, num) + 1 for num in nums]
相关推荐
该用户已不存在5 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP7 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805112 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
Fanxt_Ja12 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
c8i12 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050613 小时前
【ESP32-CAM】HELLO WORLD
python
Doris_202313 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202313 小时前
Python 模式匹配match case
前端·后端·python
这里有鱼汤14 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
元亓亓亓14 小时前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展