155. Min Stack

原创 2016年06月02日 11:34:53

155. Min Stack

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.

Example:

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

Analysis:
没怎么遇到过这样的题,没有思路。参考了这两个网址:Min Stack – LeetCode Min Stack

Source Code(C++):

#include <iostream>
#include <stack>
using namespace std;


class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> stk, minstk;
    MinStack() {

    }

    void push(int x) {
        stk.push(x);
        if (minstk.empty() || x<=minstk.top())  //注意此处必须有=
        {
            minstk.push(x);
        }
    }

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

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

    int getMin() {
        return minstk.top();
    }
};

int main() {
    MinStack sol;
    return 0;
}
版权声明:转载请注明出处,谢谢。 举报

相关文章推荐

leetcode 155 Min Stack

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

[leetcode] 155.Min Stack

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

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

LeetCode-155.Min Stack

https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retri...

LeetCode 155.Min Stack

第155题.Min Stack 问题描述: Design a stack that supports push, pop, top, and retrieving the minimum eleme...

Leetcode 155. Min Stack

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

155. Min Stack

//超时 class MinStack { public: /** initialize your data structure here. */ vector v; list...

Leetcode-155. Min Stack

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN...

155. Min Stack

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

155. Min Stack

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

【LEETCODE】155-Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)