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]
相关推荐
Vertira16 分钟前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉20 分钟前
Python之 sorted() 函数的基本语法
python
项目題供诗36 分钟前
黑马python(二十四)
开发语言·python
晓13131 小时前
OpenCV篇——项目(二)OCR文档扫描
人工智能·python·opencv·pycharm·ocr
是小王同学啊~1 小时前
(LangChain)RAG系统链路向量检索器之Retrievers(五)
python·算法·langchain
AIGC包拥它1 小时前
提示技术系列——链式提示
人工智能·python·langchain·prompt
孟陬1 小时前
Python matplotlib 如何**同时**展示正文和 emoji
python
何双新1 小时前
第 1 课:Flask 简介与环境配置(Markdown 教案)
后端·python·flask
薰衣草23332 小时前
一天两道力扣(1)
算法·leetcode·职场和发展
费弗里2 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(2)
python·dash