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]
相关推荐
hrhcode3 分钟前
【LangChain】一.LangChain v1.0-快速上手(核心组件、工具、中间件)
python·ai·langchain·agent
SunnyDays10119 分钟前
Python Word 转 Excel 详解(含整个文档、特定页面或表格转换)
python·word 转 excel·docx 转 xlsx·word 表格导出 excel
m0_7411733310 分钟前
CSS移动端实现卡片悬浮投影_利用box-shadow设置层次感
jvm·数据库·python
西洼工作室11 分钟前
uniapp+vue3+python对接阿里云短信认证服务alibabacloud_dypnsapi20170525
python·阿里云·uni-app
chushiyunen12 分钟前
pygame实现射击游戏
python·游戏·pygame
sinat_3834373613 分钟前
如何在 Laravel 中筛选并格式化匹配预定义列表的产品数据
jvm·数据库·python
2401_8463395614 分钟前
mysql如何用执行流程思维写好SQL_SQL优化方法总结
jvm·数据库·python
forEverPlume18 分钟前
SQL如何统计分组内不重复值的数量_COUNT与DISTINCT结合应用
jvm·数据库·python
chaofan98028 分钟前
突破大模型落地瓶颈:Claude 4.7 与 GPT-5.5 长上下文工程实测
数据库·人工智能·python·gpt·自动化·php·api
2501_9012005330 分钟前
PHP源码部署需要多大硬盘空间_PHP项目存储空间估算方法【方法】
jvm·数据库·python