Leetcode: Min Stack
来源:互联网 发布:python subprocess 编辑:程序博客网 时间:2024/04/30 08:26
题目:
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++代码示例:
#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(); }};
0 0
- LeetCode[stack]: Min Stack
- [leetcode][stack] Min Stack
- 【Leetcode】Min Stack
- Leetcode: Min Stack
- leetcode Min stack
- Min Stack -- LeetCode
- Leetcode: Min Stack
- 【LeetCode】Min Stack
- leetcode Min Stack
- leetcode--Min Stack
- [Leetcode]Min stack
- leetcode:Min Stack
- leetcode 之 Min Stack
- leetcode Min Stack
- LeetCode(155) Min Stack
- [LeetCode]Min Stack
- leetcode:Min Stack
- leetcode - Min Stack
- android LinearLayout比例布局
- 《c primer plus》编程练习回顾-第三章
- 其他可用的时间函数
- 能pingt通外部的Ip和dns,但上不了网络
- 第一章---网络基础知识
- Leetcode: Min Stack
- 基于Java LinkedList,实现Android大数据缓存策略
- 【成都】增强使用总结
- StringBuilder
- Java虚拟机类加载方式
- Interleaving String
- 动态绑定
- 用户输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
- WinDbg调试DMP格式文件