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]
相关推荐
高洁0120 分钟前
DNN案例一步步构建深层神经网络(二)
人工智能·python·深度学习·算法·机器学习
Insight.26 分钟前
背包问题——01背包、完全背包、多重背包、分组背包(Python)
开发语言·python
Lucky高32 分钟前
Pandas库实践1_预备知识准备
python·pandas
Salt_07281 小时前
DAY 36 官方文档的阅读
python·算法·机器学习·github
k***92161 小时前
Python 科学计算有哪些提高运算速度的技巧
开发语言·python
superman超哥1 小时前
仓颉条件变量深度解析与实践:解锁高效并发同步
开发语言·python·c#·仓颉
长空任鸟飞_阿康1 小时前
LangGraph 技术详解:基于图结构的 AI 工作流与多智能体编排框架
人工智能·python·langchain
love530love2 小时前
ComfyUI 升级 v0.4.0 踩坑记录:解决 TypeError: QM_Queue.task_done() 报错
人工智能·windows·python·comfyui
阿坤带你走近大数据2 小时前
Python基础知识-数据结构篇
开发语言·数据结构·python
小智RE0-走在路上2 小时前
Python学习笔记(7)--集合,字典,数据容器总结
笔记·python·学习