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]
相关推荐
小林ixn9 分钟前
从 List 切片到 LLM 调用:一篇搞定 Python 基础与 AI 接口
python·ai编程
sugar__salt15 分钟前
从Python列表切片到LLM接口实战:零基础AI编程落地教程
开发语言·python·ai·prompt·transformer·ai编程
乐于分享的阿乐17 分钟前
Miniconda3 超详细安装配置教程(附安装包及学习资料)
python
gis分享者26 分钟前
从原理到落地,Python 实现客户细分与销量预测
python·客户细分,销量预测,商业智能
小熊Coding43 分钟前
Python二手图书市场行为分析系统
开发语言·爬虫·python·django·计算机毕业设计·数据可视化分析·二手图书分析系统
AI算法沐枫1 小时前
机器学习经典小项目4:泰坦尼克号生存预测
人工智能·python·深度学习·线性代数·算法·机器学习·回归
洛水水1 小时前
【力扣100题】60.缺失的第一个正数
leetcode·哈希算法
威尔逊·柏斯科·希伯理1 小时前
机器学习第一天(共12天)
人工智能·python·机器学习·conda·numpy·pandas·matplotlib
愈努力俞幸运1 小时前
python 三引号
android·开发语言·python