Sword Finger Offer Interview Question 30. min関数を使用したスタック[単純]

LeetCode155と同じ

私の解決策:

2つのスタックを使用し、1つは通常のデータを保存し、i番目の要素を保存する前に最小の要素を確認します

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> a,b;
    MinStack() {

    }
    
    void push(int x) {
        a.push(x);
        if(b.empty())   b.push(x);
        else{
            int t=b.top();
            b.push((x<t)?x:t);
        }
    }
    
    void pop() {
        a.pop();
        b.pop();
    }
    
    int top() {
        return a.top();
    }
    
    int min() {
        return b.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->min();
 */

オリジナルの記事を65件公開 いいね1 訪問数488

おすすめ

転載: blog.csdn.net/qq_41041762/article/details/105463747