首页 > 其他 > 详细

【LeetCode】155. 最小栈

时间:2020-03-10 22:34:33      阅读:47      评论:0      收藏:0      [点我收藏+]

题目

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

  • push(x)?-- 将元素 x 推入栈中。
  • pop()?-- 删除栈顶的元素。
  • top()?-- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

本题同【剑指Offer】面试题30. 包含min函数的栈

思路

把每次的最小值(之前最小值和新压入栈元素较小者)都保存在辅助栈中。辅助栈的栈顶元素永远保存当前最小值。

  1. 如果新压入栈元素小于辅助栈栈顶元素,则将该元素压入辅助栈;
  2. 否则,再次将栈顶元素压入辅助栈。

代码

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

另一种写法

如果当前元素大于栈顶元素,则不压入(节省一定空间),而在上一种方法中则重复压入最小栈栈顶元素(节省弹出时间)。

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

【LeetCode】155. 最小栈

原文:https://www.cnblogs.com/galaxy-hao/p/12458890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!