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]
相关推荐
该用户已不存在7 分钟前
Python正在死去,2026年Python还值得学吗?
后端·python
战南诚10 分钟前
flask之“应用上下文,请求上下文”
python·flask
Predestination王瀞潞1 小时前
Windows环境下Pytorch的配置
人工智能·pytorch·python
二川bro1 小时前
特征工程完全手册:2025 Python实战技巧
开发语言·python
元亓亓亓2 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
用户2345267009822 小时前
Python实现异步任务队列深度好文
后端·python
夫唯不争,故无尤也2 小时前
PyTorch 的维度变形一站式入门
人工智能·pytorch·python
熊猫钓鱼>_>2 小时前
从零开始构建RPG游戏战斗系统:实战心得与技术要点
开发语言·人工智能·经验分享·python·游戏·ai·qoder
2501_941143733 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
BoBoZz193 小时前
TriangleStrip连续三角带
python·vtk·图形渲染·图形处理