LC 2034. 股票价格波动

题目描述

这是 LeetCode 上的 2034. 股票价格波动 ,难度为 中等

给你一支股票价格的数据流,数据流中每一条记录包含一个时间戳和该时间点股票对应的价格。

不巧的是,由于股票市场内在的波动性,股票价格记录可能不是按时间顺序到来的。

某些情况下,有的记录可能是错的。如果两个有相同时间戳的记录出现在数据流中,前一条记录视为错误记录,后出现的记录更正前一条错误的记录。

请你设计一个算法,实现:

  • 更新股票在某一时间戳的股票价格,如果有之前同一时间戳的价格,这一操作将更正之前的错误价格。
  • 找到当前记录里最新股票价格,最新股票价格定义为时间戳最晚的股票价格。
  • 找到当前记录里股票的最高价格。
  • 找到当前记录里股票的最低价格。

请你实现 StockPrice 类:

  • StockPrice() 初始化对象,当前无股票价格记录。
  • void update(int timestamp, int price) 在时间点 timestamp 更新股票价格为 price
  • int current() 返回股票最新价格。
  • int maximum() 返回股票最高价格。
  • int minimum() 返回股票最低价格。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
输入:
["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
输出:
[null, null, null, 5, 10, null, 5, null, 2]

解释:
StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // 时间戳为 [1] ,对应的股票价格为 [10] 。
stockPrice.update(2, 5); // 时间戳为 [1,2] ,对应的股票价格为 [10,5] 。
stockPrice.current(); // 返回 5 ,最新时间戳为 2 ,对应价格为 5
stockPrice.maximum(); // 返回 10 ,最高价格的时间戳为 1 ,价格为 10
stockPrice.update(1, 3); // 之前时间戳为 1 的价格错误,价格更新为 3
// 时间戳为 [1,2] ,对应股票价格为 [3,5] 。
stockPrice.maximum(); // 返回 5 ,更正后最高价格为 5
stockPrice.update(4, 2); // 时间戳为 [1,2,4] ,对应价格为 [3,5,2] 。
stockPrice.minimum(); // 返回 2 ,最低价格时间戳为 4 ,价格为 2

提示:

  • $1 <= timestamp, price <= 10^9$
  • updatecurrentmaximumminimum 总调用次数不超过 $10^5$
  • currentmaximumminimum 被调用时,update 操作至少已经被调用过一次

模拟 + 数据结构

容易想到我们需要使用「哈希表」来记录 {时间:价格} 的映射关系。

关于 current 操作,我们可以维护一个最大的时间戳 cur,在调用 current 的时候直接 $O(1)$ 查得结果。

然后考虑解决 update 操作中对相同时间点的更新问题,我们可以使用 TreeMap(红黑树)来解决该问题。以 {价格:该价格对应的时间点数量}KV 形式进行存储,key 按照「升序」进行排序。

然后对传入的 timestamp 是否已经被记录(是否已经存在哈希表中)进行分情况讨论:

  • 传入的 timestamp 未被记录,直接更新哈希表和 TreeMap
  • 传入的 timestamp 已被记录,此时需要先从哈希表取出旧价格 old,然后用旧价格对 TreeMap 进行修改(如果该价格只有一个时间点,将该价格直接从 TreeMap 中移除;若有多个时间点,则对该价格对应的时间点数量进行减一操作),然后再使用传入的新价格 price 更新哈希表和 TreeMap

minimummaximum 操作则只需要取得 TreeMap 的首尾 Key 即可。

Java 代码:

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
class StockPrice {
int cur;
Map<Integer, Integer> map = new HashMap<>();
TreeMap<Integer, Integer> ts = new TreeMap<>();
public void update(int timestamp, int price) {
cur = Math.max(cur, timestamp);
if (map.containsKey(timestamp)) {
int old = map.get(timestamp);
int cnt = ts.get(old);
if (cnt == 1) ts.remove(old);
else ts.put(old, cnt - 1);
}
map.put(timestamp, price);
ts.put(price, ts.getOrDefault(price, 0) + 1);
}
public int current() {
return map.get(cur);
}
public int maximum() {
return ts.lastKey();
}
public int minimum() {
return ts.firstKey();
}
}

C++ 代码:
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
class StockPrice {
public:
int cur;
unordered_map<int, int> timePriceMap;
map<int, int> priceCount;

StockPrice() : cur(0) {}

void update(int timestamp, int price) {
cur = max(cur, timestamp);
if (timePriceMap.count(timestamp)) {
int oldPrice = timePriceMap[timestamp];
if (--priceCount[oldPrice] == 0) {
priceCount.erase(oldPrice);
}
}
timePriceMap[timestamp] = price;
priceCount[price]++;
}
int current() {
return timePriceMap[cur];
}
int maximum() {
return priceCount.rbegin()->first;
}
int minimum() {
return priceCount.begin()->first;
}
};

Python 代码:
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
class StockPrice:

def __init__(self):
self.cur_time = 0
self.time_price = {}
self.price_count = defaultdict(int)
self.sorted_prices = SortedList()

def update(self, timestamp: int, price: int) -> None:
self.cur_time = max(self.cur_time, timestamp)
if timestamp in self.time_price:
old_price = self.time_price[timestamp]
self.price_count[old_price] -= 1
if self.price_count[old_price] == 0:
self.sorted_prices.discard(old_price)
self.time_price[timestamp] = price
if self.price_count[price] == 0:
self.sorted_prices.add(price)
self.price_count[price] += 1

def current(self) -> int:
return self.time_price[self.cur_time]

def maximum(self) -> int:
return self.sorted_prices[-1] if self.sorted_prices else -1

def minimum(self) -> int:
return self.sorted_prices[0] if self.sorted_prices else -1

  • 时间复杂度:令 $n$ 为最大调用次数,update 复杂度为 $O(\log{n})$;currentmaximumminimum 操作复杂度为 $O(1)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.2034 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。