文章

2034. 股票价格波动(Rating 1831)

2034. 股票价格波动(Rating 1831)

以下内容偏向于记录个人练习过程及思考,非常规题解内容

题目

2034. 股票价格波动

Rating 1831

思路

熟练使用有序容器。python中有两个比较好用的有序容器

1
2
from sortedcontainers import SortedList
from sortedcontainers import SortedDict

SortedList相当于c++中的multiset,SortedDict相当于c++中的map

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class StockPrice:
    def __init__(self):
        self.dct = SortedDict()
        self.lst = SortedList()
        

    def update(self, timestamp: int, price: int) -> None:
        if timestamp in self.dct:
            self.lst.remove(self.dct[timestamp])
        self.dct[timestamp] = price
        self.lst.add(price)
        

    def current(self) -> int:
        t, p = self.dct.popitem()
        self.dct[t] = p
        return p
        

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

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


# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()
本文由作者按照 CC BY 4.0 进行授权