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();
}
}
发表回复