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]
相关推荐
初学者,亦行者4 小时前
利用pyecharts自动化绘制漏斗图保姆级教程
python·信息可视化·数据分析
这就是佬们吗4 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm
卷无止境5 小时前
提升 Python 代码健壮性的方法大盘点
后端·python
asdzx675 小时前
Python PDF 拆分实战指南:单页拆分与按需页码范围拆分
开发语言·python·pdf
LadenKiller5 小时前
近期AI训练量化表达,解释改写检查要按顺序
人工智能·python
李昊哲小课5 小时前
咖啡工坊 · FastAPI 22 章教程合集
服务器·人工智能·python·fastapi
小肝一下5 小时前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
卷无止境5 小时前
Python 异常处理:从入门到工程实践
后端·python
garuda herb5 小时前
生成专题页Blog--建立并返回 MySQL 数据库连接
python·mysql
ONE_SIX_MIX5 小时前
qwenpaw-plugin-file-tools QwenPaw增强文件工具 更新 v1.1.1
python·qwenpaw