码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Min Stack

时间:2015-06-07 06:10:12      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

The idea is to use two stacks.

For push, the first stack records the pushed elements and the second stack records all the minimum (including duplicates) that have been seen.

For pop, we need to compare with the top elements of the two stacks. If they are equal (the top element is also minimum, popping it out will change the minimum), pop both; otherwise, only pop the first stack.

The remaining top and getMin will be trivial: just return the top element of the first and second stack respectively.

The code is as follows.

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         if (stk1.empty() || x <= stk2.top())
 5             stk2.push(x);
 6         stk1.push(x);
 7     }
 8 
 9     void pop() {
10         if (stk1.top() == stk2.top())
11             stk2.pop();
12         stk1.pop();
13     }
14 
15     int top() {
16         return stk1.top();
17     }
18 
19     int getMin() {
20         return stk2.top();
21     }
22 private:
23     stack<int> stk1; 
24     stack<int> stk2;
25 };

 

[LeetCode] Min Stack

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4557627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!