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]
相关推荐
方知我18 分钟前
NumPy一小时速成
开发语言·python·numpy
IPdodo_21 分钟前
静态 IP 访问异常排查:403/429 归因与迁移验收
服务器·网络·数据库·python·网络协议·php·性能测试
Zengs30 分钟前
Python 脚本日志怎么分级落盘?排错时一次找准现场
python
baopixiaoz1 小时前
BeeQuant × BeeAgent:AI量化新范式
大数据·人工智能·python·区块链
IT毕设实战小研1 小时前
基于大数据的AI应用对就业与收入增长的区域差异分析及可视化
大数据·人工智能·python·随机森林·机器学习·课程设计
摆烂老大2 小时前
论文学习 | Expert Systems With Applications2026 | 可微分建模:S4D-HBV
python·学习·水文
程序员夏洛2 小时前
谈谈你了解的最常见的几种设计模式,说说他们的应用场景
开发语言·python·模板方法模式
橙露2 小时前
Cloudflare Pages 深度评测:免费静态托管的香与坑
python·部署
lk123062 小时前
【无标题】
pytorch·python
数据开发 Yang 同学2 小时前
【Python 并发编程】线程、进程、协程、同步/异步一次说清
python