[LeetCode]Min Stack
来源:互联网 发布:c语言考试卷 编辑:程序博客网 时间:2024/06/06 14:01
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.
实现栈的常规操作,其中getMin()要求用常数时间获取栈中当前最小元素。
分析:
用空间换时间:在栈A(原本的栈)外多用一个向栈顶递减的栈B。
插入值时如果值要小于或等于栈B顶元素,就将它同时压入栈A和B,否则只压入A;A的元素出栈时如果栈顶元素恰好等于B栈顶元素则同时B出栈。
class MinStack {public:void push(int x) {realStk.push(x);if (miniStk.empty() || x <= miniStk.top())miniStk.push(x);}void pop() {if (realStk.top() == miniStk.top())miniStk.pop();realStk.pop();}int top() {return realStk.top();}int getMin() {return miniStk.top();}private:stack<int> realStk;stack<int> miniStk;};
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
- groovy 速学 - 04 - 操作符
- (1)设计模式:责任链模式
- 如何实现C++调用C#的dll方法教程
- poj 4046 Sightseeing 枚举思想在spfa中的应用
- 如何使用Java、Servlet创建二维码
- [LeetCode]Min Stack
- 在Ubuntu上搭建SVN服务器
- JAVA_HOME之小配置,大问题
- Linux入门:VIM
- LeetCode - Pow(x, n)
- final、public、abstract可以修饰外部class
- Android Gif播放控件
- git 合并两个远程库
- C++学习笔记(一)