首页 > 其他 > 详细

【leetcode】Min Stack

时间:2015-05-20 18:19:15      阅读:202      评论:0      收藏:0      [点我收藏+]

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.

 

 1 class MinStack {
 2 private:
 3     stack<int> stk;
 4     stack<int> minstack;
 5 public:
 6     void push(int x) {
 7         stk.push(x);
 8         if(minstack.empty())
 9         {
10             minstack.push(x);
11         }else
12         {
13             if(x<=minstack.top())
14                 minstack.push(x);
15         }
16     }
17 
18     void pop() {
19         if(stk.top()==minstack.top())
20         {
21             stk.pop();
22             minstack.pop();
23         }else
24         {
25             stk.pop();
26         }
27     }
28 
29     int top() {
30         return stk.top();
31     }
32 
33     int getMin() {
34         return minstack.top();
35     }
36 };

 

【leetcode】Min Stack

原文:http://www.cnblogs.com/jawiezhu/p/4517706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!