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]
相关推荐
️停云️26 分钟前
【滑动窗口与双指针】不定长滑动窗口
c++·算法·leetcode·剪枝·哈希
!chen1 小时前
Error: error:0308010C:digital envelope routines::unsupporte
python
小北方城市网2 小时前
分布式锁实战指南:从选型到落地,避开 90% 的坑
java·数据库·redis·分布式·python·缓存
xiaolyuh1232 小时前
【XXL-JOB】 GLUE模式 底层实现原理
java·开发语言·前端·python·xxl-job
likuolei2 小时前
Spring AI框架完整指南
人工智能·python·spring
二哈喇子!2 小时前
PyTorch生态与昇腾平台适配:环境搭建与详细安装指南
人工智能·pytorch·python
Learner2 小时前
Python数据类型(三):列表和元组
开发语言·python
世界唯一最大变量2 小时前
用自创的算法快速解决拉姆奇数
python
leluckys2 小时前
AI- 一种快速实现MCP服务的方法
开发语言·python
写代码的【黑咖啡】3 小时前
探索 Python 中的 Vaex:高效处理大规模数据的新选择
开发语言·python