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]
相关推荐
Jurio.1 分钟前
Python Ray 分布式计算应用
linux·开发语言·python·深度学习·机器学习
爱加糖的橙子14 分钟前
Dify升级到Dify v1.10.1-fix修复CVE-2025-55182漏洞
人工智能·python·ai
Pyeako41 分钟前
python网络爬虫
开发语言·爬虫·python·requsets库
diegoXie41 分钟前
【Python】 中的 * 与 **:Packing 与 Unpacking
开发语言·windows·python
鹿角片ljp1 小时前
力扣140.快慢指针法求解链表倒数第K个节点
算法·leetcode·链表
程序员杰哥2 小时前
如何用Postman做接口自动化测试?
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
xxxxxmy2 小时前
同向双指针(滑动窗口)
python·算法·滑动窗口·同向双指针
测试19982 小时前
selenium自动化测试详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
勇气要爆发2 小时前
【第一阶段—基础准备】第五章:Python模块和包管理(基础篇)—变形金刚的装备库
开发语言·python