Leetcode14 - 155. Minimal stack

insert image description here

Law one:

class MinStack {
    
    
public:

    stack<int>st;
    stack<int>helper;
    MinStack() {
    
    
   
    }
    
    void push(int val) {
    
    
       st.push(val);
       if(helper.empty()||helper.top()>val)helper.push(val);
       else helper.push(helper.top());
    }
    
    void pop() {
    
    
        st.pop();
        helper.pop();
    }
    
    int top() {
    
    
         return st.top();
    }
    
    int getMin() {
    
    
        return helper.top();

    }
};

Method two:

class MinStack {
    
    
public:

    stack<pair<int,int>>st;
   
    MinStack() {
    
    
   
    }
    
    void push(int val) {
    
    
       if(st.empty()||st.top().second>val){
    
    
          st.push({
    
    val,val});
          
       }else{
    
    
           st.push({
    
    val,st.top().second});
       } 

    }
    
    void pop() {
    
    
        st.pop();
    }
    
    int top() {
    
    
         return st.top().first;
    }
    
    int getMin() {
    
    
        return st.top().second;

    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324117098&siteId=291194637