前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Min Stack

Leetcode: Min Stack

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-25 14:44:59
6070
发布2019-01-25 14:44:59
举报

题目: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

思路分析: 用两个stack来维护这个MinStack结构。1个stack用来正常进行stack的push pop等操作。另外1个stack用来维护min.每次对stack进行pop或者push时,也对min_stack进行相应操作。

C++代码示例:

代码语言:javascript
复制
#include <stack>

using namespace std;

class MinStack 
{
private:
    stack<int> stk;
    stack<int> min;
public:
    void push(int x)
    {
        stk.push(x);
        if (min.empty())
        {
            min.push(x);
        }
        else
        {
            //注意这里是>=,我第一次用>结果报错了
            if (min.top() >= x)
            {
                min.push(x);
            }
        }
    }

    void pop()
    {
        if (stk.top() == min.top())
        {
            min.pop();
        }
        stk.pop();
    }

    int top()
    {
        return stk.top();
    }

    int getMin()
    {
        return min.top();
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月07日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档