LeetCode 2034. 股票价格波动
2034. 股票价格波动
Solution
思路一:有序集合+哈希表
查询最新股票价格:维护最大的时间戳 哈希表直接查询。
最高,最低价格查询:维护股票价格的有序集合。
由于存在不同时间戳有相同的股票价格,因此股票价格需要记录出现次数,更新的时候维护即可。
class StockPrice {
int curTimestamp;
HashMap<Integer, Integer> timePricestamp;
TreeMap<Integer, Integer> priceCnt;
public StockPrice() {
curTimestamp = 0;
timePricestamp = new HashMap<>();
priceCnt = new TreeMap<>();
}
public void update(int timestamp, int price) {
curTimestamp = Math.max(curTimestamp, timestamp);
if (timePricestamp.containsKey(timestamp)) {
int oldPrice = timePricestamp.get(timestamp);
int cnt = priceCnt.get(oldPrice);
if (cnt == 1) {
priceCnt.remove(oldPrice);
} else {
priceCnt.put(oldPrice, cnt - 1);
}
}
priceCnt.put(price, priceCnt.getOrDefault(price, 0) + 1);
timePricestamp.put(timestamp, price);
}
public int current() {
return timePricestamp.get(curTimestamp);
}
public int maximum() {
return priceCnt.lastKey();
}
public int minimum() {
return priceCnt.firstKey();
}
}
/**
* Your StockPrice object will be instantiated and called as such:
* StockPrice obj = new StockPrice();
* obj.update(timestamp,price);
* int param_2 = obj.current();
* int param_3 = obj.maximum();
* int param_4 = obj.minimum();
*/
思路二:哈希表+两个优先级队列
如果更新的时候直接取最大值,最小值就会出现依然保存历史失效的股票价格,因此在更新的时候我们可以把所有更新数据存入最大堆,最小堆,保存时间与股票价格的对应关系,在查询最大、最小的时候,我们就从最大最小堆里查找,同时维护。如果出现和哈希表中的数据一致时,说明数据正常,不一致就是失效数据。
class StockPrice {
int curTimestamp;
HashMap<Integer, Integer> stocks;
PriorityQueue<int[]> maxPriority;
PriorityQueue<int[]> minPriority;
public StockPrice() {
curTimestamp = 0;
stocks = new HashMap<>();
maxPriority = new PriorityQueue<int[]>((a, b) -> b[0] - a[0]);
minPriority = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);
}
public void update(int timestamp, int price) {
curTimestamp = Math.max(timestamp, curTimestamp);
stocks.put(timestamp, price);
maxPriority.offer(new int[]{price, timestamp});
minPriority.offer(new int[]{price, timestamp});
}
public int current() {
return stocks.get(curTimestamp);
}
public int maximum() {
while (true) {
int[] vals = maxPriority.peek();
int price = vals[0], timestamp = vals[1];
if (stocks.get(timestamp) == price) {
return price;
}
maxPriority.poll();
}
}
public int minimum() {
while (true) {
int[] vals = minPriority.peek();
int price = vals[0], timestamp = vals[1];
if (stocks.get(timestamp) == price) {
return price;
}
minPriority.poll();
}
}
}
/**
* Your StockPrice object will be instantiated and called as such:
* StockPrice obj = new StockPrice();
* obj.update(timestamp,price);
* int param_2 = obj.current();
* int param_3 = obj.maximum();
* int param_4 = obj.minimum();
*/
埋骨何须桑梓地,人生无处不青山