随笔- 509  文章- 0  评论- 151  阅读- 22万 

Min Stack

2015.1.23 12:13

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.

Solution:

  This could almost be counted as a FAQ. You'll find a same question in "Cracking the Coding Interview". A min stack is maintained alongside the data stack, recording every minimal (so far) element. The min stack is updated whever a new minimal value is being pushed, or the current minimal value is being popped.

  Total time complexity for each operation is strictly O(1). Extra space of O(n) is required to maintain the min stack.

Accepted code:

复制代码
 1 // 1AC, old
 2 #include <stack>
 3 using namespace std;
 4 
 5 class MinStack {
 6 public:
 7     void push(int x) {
 8         if (ms.empty() || ms.top() >= x) {
 9             ms.push(x);
10         }
11         s.push(x);
12     }
13 
14     void pop() {
15         if (s.top() == ms.top()) {
16             ms.pop();
17         }
18         s.pop();
19     }
20 
21     int top() {
22         return s.top();
23     }
24 
25     int getMin() {
26         return ms.top();
27     }
28 private:
29     stack<int> s, ms;
30 };
复制代码

 

 posted on   zhuli19901106  阅读(190)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示