Prove safety offer ----- 20, containing a stack min

Copyright: https://blog.csdn.net/zl6481033/article/details/90906243

1, Title Description

        Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).

2, analysis

        Before leetcode done, ( https://blog.csdn.net/zl6481033/article/details/89568340 ).

3, Code

class Solution {
public:
    void push(int value) {
            s1.push(value);
        if(s2.empty()||s2.top()>value){
            s2.push(value);
        }
    }
    void pop() {
        if(s2.top()==s1.top()) s2.pop();
        s1.pop();
    }
    int top() {
        return s1.top();
    }
    int min() {
        return s2.top();
    }
private:
    stack<int> s1;
    stack<int> s2; 
};

4, the relevant knowledge points

        Knowledge stack.

Guess you like

Origin blog.csdn.net/zl6481033/article/details/90906243