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]
相关推荐
XZ-0700017 小时前
week4-2-坐标轴
python
Delta-delta7 小时前
Ubuntu MATE 24.04 + systemd 部署 LiteLLM + Open WebUI
python
金融大 k7 小时前
A股实时行情 API 接入指南:Python 覆盖行情、复权、基本面与 WebSocket
python·websocket·行情数据·行情 api
生信大杂烩7 小时前
Xenium H&E空间原位可视化——细胞轮廓、基因表达与转录本可视化
python·算法·数据分析
东莞市云毅网络有限公司7 小时前
用标准库做网页正文抽取:从 HTML 到结构化字段的轻量实现
python·sqlite·自动化运维·geo·数据监测
高级程序源7 小时前
django校企合作实习基地管理系统82506-计算机课程设计、毕业设计
vue.js·后端·python·mysql·django·课程设计·pygame
东方芷兰7 小时前
Agent 技术摘要 02 —— 区块链、比特币、挖矿、ETF、比特币疯涨事件、以太坊、以太币、显卡荒事件
人工智能·笔记·python
贝猫说python8 小时前
阿里云部署qwen 大模型从0-1,第2步:阿里云平台创建ubuntu实例
python
峥嵘life8 小时前
2026华为AI码道 CodeArts 使用分享:Windows端 + 服务器CLI 实战总结
android·大数据·开发语言·python
贝猫说python8 小时前
阿里云部署qwen 大模型从0-1,第3步:阿里云服务器上部署大模型
python