题目来源:https://leetcode-cn.com/problems/stock-price-fluctuation/
大致题意:
设计一个股票的操作类,可以完成四个操作:
- 更新:给定时间戳和对应的股票价格,更新给定时间的价格。若之前这个时间已有对应价格,则更新为新的价格
- 返回最新时间的股票价格
- 返回股票价格的最大值
- 返回股票价格的最小值
思路
既然是时间戳对应价格,那么就要用Map,用时间作 key,价格作 value。因为还需要返回最新时间的股票价格,所以可以使用 TreeMap,可以直接取出集合最大 key 对应的 value
而股票价格,可以用 Map 记录,将价格作为 key,然后 value 为该价格出现的次数。因为更新操作可能会删除某个价格,所以需要记录次数。
而且又要返回价格的最值,所以也用 TreeMap
代码:
class StockPrice {
// 存<时间戳, 价格>
TreeMap<Integer, Integer> time_value;
// 存<价格, 出现次数>
TreeMap<Integer, Integer> value_time;
public StockPrice() {
time_value = new TreeMap<Integer, Integer>();
value_time = new TreeMap<Integer, Integer>();
}
public void update(int timestamp, int price) {
// 若当前时间戳第一次出现
if (!time_value.containsKey(timestamp)) {
time_value.put(timestamp, price);
value_time.put(price, value_time.getOrDefault(price, 0) + 1);
}
// 当前时间戳已经出现过
else {
// 获取之前存储的价格
int lastPrice = time_value.get(timestamp);
// 更新新价格
time_value.put(timestamp, price);
// 将之前对应价格次数减 1
value_time.put(lastPrice, value_time.get(lastPrice) - 1);
if (value_time.get(lastPrice) == 0) {
value_time.remove(lastPrice);
}
// 更新新价格的次数
value_time.put(price, value_time.getOrDefault(price, 0) + 1);
}
}
public int current() {
// TreeMap 默认升序
return time_value.lastEntry().getValue();
}
public int maximum() {
return value_time.lastKey();
}
public int minimum() {
return value_time.firstKey();
}
}