美文网首页LeetCode题解
LeetCode 155. 最小栈

LeetCode 155. 最小栈

作者: 云胡同学 | 来源:发表于2018-08-27 18:06 被阅读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.

思路

使用两个栈 s1, s2,s1 正常的入栈出栈,s2 存放 s1 中所有节点的最小值。

  1. 入栈

    • 待入栈的值 x 不是最小值,s1 正常入栈,s2不操作
    • 待入栈的值 x 小于等于 s2 栈顶的值,说明有新的最小值,s1 正常入栈, 同时把 x 入到 s2 栈中,始终保持 s2 栈顶元素是最小值。
  2. 出栈

    • 出栈的值不是最小值,s1 正常出栈,s2 不操作
    • 出栈的值是最小值,s1 正常出栈,最小值要更新,所以 s2 也出栈
  3. 获取最小值

    直接就是 s2 的栈顶元素。

#include<iostream>
#include<stack>
#include<string>
using namespace std;
class MinStack {
public:
    stack<int> s1, s2;
    MinStack() {
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x <= s2.top())
        {
            s2.push(x);
        }
    }
    
    void pop() {
        if(s1.top() == s2.top())
            s2.pop();
        s1.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
};

相关文章

  • LeetCode-155-最小栈

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

  • LeetCode 155. 最小栈 | Python

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

  • LeetCode:155. 最小栈

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

  • 2.栈(二)

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

  • 155. 最小栈

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

  • 155. 最小栈

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

  • LeetCode 155. 最小栈

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

  • LeetCode 155. 最小栈

    原题地址 设置一个单调栈,每次看要压入栈的元素是否比单调栈中的顶端值小,如果小那就同时压入到单调栈中,弹出的时候,...

  • LeetCode 155. 最小栈

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

  • 栈 问题

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

网友评论

    本文标题:LeetCode 155. 最小栈

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