Leetcode 2034. 股票价格波动 (数据结构设计)

Leetcode 2034. 股票价格波动 (数据结构设计)_第1张图片

 timestamp和price用HashMap描述,再用一个变量记录当前时间,最高和最低价格用Tree_Map或者priority_queue描述。

using PII = pair;
class StockPrice {
public:
    StockPrice() {
        this->maxTimestamp = 0;
    }
    
    void update(int timestamp, int price) {
        this->maxTimestamp = max(this->maxTimestamp, timestamp);
        timePriceMap[timestamp] = price;
        pqMax.emplace(price, timestamp);
        pqMin.emplace(price, timestamp);
    }
    
    int current() {
        return timePriceMap[maxTimestamp];
    }
    
    int maximum() {
        while (true) {
            auto [price, ts] = pqMax.top();
            if (timePriceMap[ts] == price) {
                return price;
            }
            pqMax.pop();
        }
        return -1;
    }
    
    int minimum() {
        while (true) {
            auto [price, ts] = pqMin.top();
            if (timePriceMap[ts] == price) {
                return price;
            }
            pqMin.pop();
        }
        return -1;
    }
private:
    int maxTimestamp;
    unordered_map timePriceMap;
    priority_queue, less> pqMax;
    priority_queue, greater> pqMin;
};

/**
 * 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();
 */

你可能感兴趣的:(算法,leetcode,数据结构,算法)