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]
相关推荐
落羽凉笙13 小时前
Python学习笔记(3)|数据类型、变量与运算符:夯实基础,从入门到避坑(附图解+代码)
笔记·python·学习
Quintus五等升13 小时前
深度学习①|线性回归的实现
人工智能·python·深度学习·学习·机器学习·回归·线性回归
天远Date Lab13 小时前
Python实战:对接天远数据手机号码归属地API,实现精准用户分群与本地化运营
大数据·开发语言·python
哈里谢顿14 小时前
Python异常链:谁才是罪魁祸首?一探"The above exception"的时间顺序
python
AlenTech14 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
哈里谢顿14 小时前
验证 list() 会调用 `__len__` 方法的深度解析
python·django
vibag15 小时前
构建智能体与工具调用
python·语言模型·大模型·langgraph
sin_hielo15 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
小途软件15 小时前
高校宿舍访客预约管理平台开发
java·人工智能·pytorch·python·深度学习·语言模型
-dcr15 小时前
49.python自动化
运维·python·自动化