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]
相关推荐
天选之女wow22 分钟前
【Hard——Day4】25.K 个一组翻转链表
数据结构·算法·leetcode·链表
2501_9411118227 分钟前
使用Scikit-learn进行机器学习模型评估
jvm·数据库·python
小呀小萝卜儿1 小时前
2025-11-14 学习记录--Python-使用sklearn+检测 .csv 文件的编码+读取 .csv 文件
python·学习
java1234_小锋1 小时前
[免费]基于python的Flask+Vue医疗疾病数据分析大屏可视化系统(机器学习随机森林算法+requests)【论文+源码+SQL脚本】
python·机器学习·数据分析·flask·疾病数据分析
MediaTea3 小时前
Python 第三方库:cv2(OpenCV 图像处理与计算机视觉库)
开发语言·图像处理·python·opencv·计算机视觉
江塘3 小时前
机器学习-决策树多种生成方法讲解及实战代码讲解(C++/Python实现)
c++·python·决策树·机器学习
多彩电脑3 小时前
死循环逻辑检测
数据结构·python·算法·动态规划
YongCheng_Liang3 小时前
Python 基础核心模块全解析:从入门到实践的知识框架
python
RanMatrix3 小时前
python-logging模块
python
e***74953 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python