其他分享
首页 > 其他分享> > [Google] LeetCode 2034 Stock Price Fluctuation

[Google] LeetCode 2034 Stock Price Fluctuation

作者:互联网

You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.

Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.

Design an algorithm that:

Implement the StockPrice class:

Solution

构造一个大根堆和小根堆,这里可以用 \(priority\_queue\) 来实现。但是我们还需要删除队列中的任何一个元素,这里我们额外使用一个相同的队列,将需要删除的元素 \(push\) 进去。求 \(top\) 的时候只需要利用 \(while\) 来 \(pop\) 出相同的队首元素即可。

点击查看代码
class StockPrice {
private:
    map<int,int> record;
    priority_queue<int> ts;
    
    typedef struct _MAXHEAP {
        priority_queue<int> Q,D;
        void push(int x) {Q.push(x);}
        void erase(int x) {D.push(x);}
        bool empty() {
            return Q.empty();
        }
        int top() {
            while(!D.empty()&&Q.top()==D.top()) {Q.pop();D.pop();}
            return Q.empty()?0:Q.top();
        }
    } MAXHEAP;
    
    typedef struct _MINHEAP {
        priority_queue<int, vector<int>, greater<int> > Q,D;
        void push(int x) {Q.push(x);}
        void erase(int x) {D.push(x);}
        bool empty() {
            return Q.empty();
        }
        int top() {
            while(!D.empty()&&Q.top()==D.top()) {Q.pop();D.pop();}
            return Q.empty()?0:Q.top();
        }
    } MINHEAP;
    
    MAXHEAP maxQ;
    MINHEAP minQ;
    
public:
    StockPrice() {
        
    }
    
    void update(int timestamp, int price) {
        if(!record[timestamp]){
            record[timestamp] = price;
            maxQ.push(price);
            minQ.push(price);
            ts.push(timestamp);
        }
        else{
            int prev = record[timestamp];
            maxQ.erase(prev); minQ.erase(prev);
            record[timestamp] = price;
            maxQ.push(price); minQ.push(price);
        }
        
    }
    
    int current() {
        return record[ts.top()];
    }
    
    int maximum() {
        return maxQ.top();
    }
    
    int minimum() {
        return minQ.top();
    }
};

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

标签:Google,int,Fluctuation,Price,top,timestamp,push,price,stock
来源: https://www.cnblogs.com/xinyu04/p/16608921.html