class StockPrice {
// key: timestamp; value: price
private Map data;
// key: price; value: times that happens
private TreeMap rank;
// 记录当前最新的时间点
private Integer latestTime;
public StockPrice() {
data = new HashMap<>();
rank = new TreeMap<>();
latestTime = 0;
}
public void update(int timestamp, int price) {
// 获取最新的时间点
latestTime = timestamp > latestTime ? timestamp : latestTime;
Integer oldVal = null;
// 获取老的价格
if(data.containsKey(timestamp)){
oldVal = data.get(timestamp);
}
// 在data中更新或新增数据
data.put(timestamp, price);
// 如果存储过,需要更新,价格
if(oldVal != null){
// 如果新老价格一样则直接返回
if(oldVal == price)
return;
Integer times = rank.get(oldVal);
if(times == 1){
// 将数据从排行榜中删除
rank.remove(oldVal);
}else{
// 删除一条价格为oldVal的数据
rank.put(oldVal, times - 1);
}
}
// 获取之前这个价格出现的次数
// null 代表从未出现过
Integer times = rank.get(price);
if(times == null)
rank.put(price, 1);
else{
rank.put(price, times + 1);
}
}
public int current() {
// 获取当前最新的价格
return data.get(latestTime);
}
public int maximum() {
// 获取最大的价格
return rank.lastKey();
}
public int minimum() {
// 获取最小的价格
return rank.firstKey();
}
}