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

【leetcode】Min Stack

时间:2015-05-20 18:21:04      阅读:116      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!