[leetcode]18 Min Stack

来源:互联网 发布:淘宝卖家服务市场 编辑:程序博客网 时间:2024/05/02 00:04

题目链接:https://leetcode.com/problems/min-stack/
Runtimes:71ms

1、问题

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.

2、分析

一开始没理解题意,以为是简单的一个获取最小值的栈,后来跑了几次出现错误,重新看题目,发现有一个关键的单词是constant。恍然大悟,要常量时间内获得栈的最小值。因为一篇文章受到启发,开多一个栈来记录当前栈的最小值,只有比栈顶元素小的值才会被记录下来,因此最终可以得到一个栈底到栈顶单调递减的栈。

3、小结

一开始以为不能用stack库,所以用数组来代替,麻烦好多。看题目要看仔细,这很重要。

4、实现

class MinStack {public:    void push(int x) {        st.push(x);        if(stm.empty() || stm.top() >= x)            stm.push(x);    }    void pop() {        int temp = st.top();         st.pop();        if(temp == stm.top())             stm.pop();    }    int top() {        return st.top();    }    int getMin() {        return stm.top();    }private:    stack <int> st;    stack <int> stm;};

5、反思

熟悉stack的一些基本操作,要总结一下stack,并了解stl如何实现stack。
文章链接:http://www.cnblogs.com/x1957/p/4086448.html

0 0
原创粉丝点击