2034. 股票价格波动
approach 1,有序集合+哈希表
class StockPrice {
TreeMap<Integer, Integer> tm = new TreeMap<>();
Map<Integer, Integer> map = new HashMap<>();
public StockPrice() {
}
int last = Integer.MIN_VALUE;
int lp = 0;
public void update(int timestamp, int price) {
if (timestamp >= last) {
last = timestamp;
lp = price;
}
Integer pre = map.get(timestamp);
map.put(timestamp, price);
tm.put(price, tm.getOrDefault(price, 0) + 1);
if (pre != null) {
Integer cnt = tm.get(pre);
if (cnt > 1) {
tm.put(pre, tm.getOrDefault(pre, 0) - 1);
} else {
tm.remove(pre);
}
}
}
public int current() {
return lp;
}
public int maximum() {
return tm.lastKey();
}
public int minimum() {
return tm.firstKey();
}
}
class StockPrice {
Map<Integer, Integer> map = new HashMap<>();
TreeSet<Integer> ts = new TreeSet<>((a, b) -> {
return map.get(a) - map.get(b);
});
int last = 0;
int lastTime = 0;
public StockPrice() {
}
public void update(int timestamp, int price) {
Integer p = map.get(timestamp);
if (p != null) ts.remove(timestamp);
map.remove(timestamp);
map.put(timestamp, price);
ts.add(timestamp);
if (timestamp >= lastTime) {
lastTime = timestamp;
last = price;
}
}
public int current() {
return last;
}
public int maximum() {
return map.get(ts.last());
}
public int minimum() {
return map.get(ts.first());
}
}