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]
相关推荐
今天AI了吗9 分钟前
从聊天到委派:AI Agent 如何推进长期任务
数据库·人工智能·python·sql·rust
土司大王12 分钟前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
傻啦嘿哟25 分钟前
王者荣耀爬虫:爬取全英雄皮肤数据,用Python做可视化分析
开发语言·爬虫·python
徒慕风流34 分钟前
激光雷达回波信号滤波与时刻鉴别算法:原理、代码实现与仿真验证
python·算法·激光雷达
菜冻鱼38 分钟前
Python-pytorch-数据加载
开发语言·人工智能·pytorch·python·深度学习·机器学习
you鬰40 分钟前
datawhale--llm-algo-leetcod1️⃣
python·datawhale
南京云森杉木桩1 小时前
水利木桩源头直供,质量可靠价格更优
大数据·python
Aaron - Wistron1 小时前
Python基础教程2/4(复合数据结构)
python
小柯南敲键盘1 小时前
跨境电商图片翻译与视频字幕翻译工具推荐
python·音视频
ZC跨境爬虫2 小时前
LeetCode 13. 罗马数字转整数(多解法详解 + Java Python 实现)
java·python·leetcode