栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【leetcode 每日打卡】2034. 股票价格波动

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【leetcode 每日打卡】2034. 股票价格波动

from sortedcontainers import SortedList

class StockPrice:
    def __init__(self):
        self.price = SortedList()
        self.timePriceMap = {}
        self.maxTimestamp = 0

    def update(self, timestamp: int, price: int) -> None:
        if timestamp in self.timePriceMap:
            self.price.discard(self.timePriceMap[timestamp])
        self.price.add(price)
        self.timePriceMap[timestamp] = price
        self.maxTimestamp = max(self.maxTimestamp, timestamp)

    def current(self) -> int:
        return self.timePriceMap[self.maxTimestamp]

    def maximum(self) -> int:
        return self.price[-1]

    def minimum(self) -> int:
        return self.price[0]

1.SortedList()是python中一个专门提供排序的库,通过add()增加,discard()删除(即使不存在数据也不会报错),增加到数组的数字会从小到大自动排序,这样就可以通过[0]来访问数组最小值,[-1]来访问数组最大值。

2.首先初始化类,price代表一个从小到大自动排序的价格表,timePriceMap存放的是时间点所对应的价格,maxTimestamp代表是当前的时间,也就是最大的时间戳。

3.先判断当前时间戳是否已经存在,如果存在就删除内容,然后就将当前时间戳所对应的价格存入timePriceMap的字典中,并且将价格放入SortedList自动排序,通过max()和当前时间戳的大小进行比对从而进行更新最新时间。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/724818.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号