美文网首页
155. 最小栈

155. 最小栈

作者: HamletSunS | 来源:发表于2019-08-10 15:26 被阅读0次

思路:
每次往栈中压入两个元素,1个是实际要入栈的元素,1个是当前栈中的最小元素。这样是为了方便迅速查找到当前栈中的最小元素

设计:
入栈 先判空,若是,那么最小元素min与第一个元素el相等,连续入栈2个el;若不是,先top()看一下未入栈时的最小元素min,再入栈el,最后入栈最小元素(通过比较min和新入栈的el来决定)

出栈 先判空,若非空,则连续出2个元素(第一个是min,第二个是el)

取最小值 直接st.top(注意st与自己的栈是两回事)

top 先判空。。。先保存min,出栈,top看el,然后把min入栈

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        if(st.empty()){            
            st.push(x);
            st.push(x);
        }
        else{
            int min=st.top();
            st.push(x);
            if(x<min)
                st.push(x);              
                
            else
                st.push(min);
        }
    }
    
    void pop() {
        if(!st.empty()){
            st.pop();
            st.pop();
        }      
        
    }
    
    int top() {
        int min=st.top();
        st.pop();
        int ret=st.top();
        st.push(min);
        return ret;
    }
    
    int getMin() {
        return st.top();
    }
private: 
    stack<int> st;
  
};

相关文章

  • LeetCode-155-最小栈

    LeetCode-155-最小栈 155. 最小栈[https://leetcode-cn.com/problem...

  • 栈 问题

    155. 最小栈 常数时间内检索最小元素 使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。...

  • LeetCode:最小栈

    155. 最小栈 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。push(...

  • LeetCode 155. 最小栈 | Python

    155. 最小栈 题目来源:https://leetcode-cn.com/problems/min-stack ...

  • LeetCode:155. 最小栈

    问题链接 155. 最小栈[https://leetcode-cn.com/problems/min-stack/...

  • LeetCode刷题笔记(三)栈与队列

    三. 栈与队列 python中的栈直接用list实现,队列用deque,需要导入外部包。 155. 最小栈 题目:...

  • 2.栈(二)

    题目汇总:https://leetcode-cn.com/tag/stack/155. 最小栈简单[✔]173. ...

  • LeetCodeDay24 —— 最小栈

    155. 最小栈 描述 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。 pus...

  • 155. 最小栈

    155. 最小栈[https://leetcode.cn/problems/min-stack/] 设计一个支持 ...

  • 155. 最小栈

    题目地址(155. 最小栈) https://leetcode.cn/problems/min-stack/[ht...

网友评论

      本文标题:155. 最小栈

      本文链接:https://www.haomeiwen.com/subject/myerjctx.html