Media
Google
https://leetcode.com/problems…
class StockPrice {
// key: time, value: price
private Map<Integer, Integer> timePrice;
// key: price, value: frequency,应用 tree map,使得依照 price 从小到大排序,不便间接获取 max / min
private TreeMap<Integer, Integer> priceFreq;
private int latestTime; // 最新的工夫
public StockPrice() {timePrice = new HashMap<>();
latestTime = 0;
priceFreq = new TreeMap<>();}
public void update(int timestamp, int price) {
// 更新最新工夫,始终让 latestTime 放弃为最近的工夫戳,在调用 current 办法时,间接从 map 中获取
latestTime = Math.max(latestTime, timestamp);
// 如果工夫戳之前保留过,那么对频率表进行更新
if (timePrice.containsKey(timestamp)) {
// 依据工夫戳,拿到之前的旧 price
int oldPrice = timePrice.get(timestamp);
// 因为更改了,所以把频率 -1
priceFreq.put(oldPrice, priceFreq.get(oldPrice) - 1);
// 如果该 price 频率更改后为 0,那么须要移除该 price
if (priceFreq.get(oldPrice) == 0) priceFreq.remove(oldPrice);
}
// 别离更新两个 map 中的新的 price
timePrice.put(timestamp, price);
priceFreq.put(price, priceFreq.getOrDefault(price, 0) + 1);
}
public int current() {
// 依据最新工夫间接获取 price
return timePrice.get(latestTime);
}
public int maximum() {
// 从 priceFreq 中间接取最初那个最大 price
return priceFreq.lastKey();}
public int minimum() {
// 从 priceFreq 中间接取第一个最小的 price
return priceFreq.firstKey();}
}