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

leetcode 155. Min Stack

时间:2015-01-07 23:21:50      阅读:181      评论: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 public:
 3     void push(int x) 
 4     {
 5         if (minS.empty() || x <= minS.top())
 6             minS.push(x);
 7         S.push(x);
 8     }
 9 
10     void pop() 
11     {
12         if (minS.top() == S.top())
13             minS.pop();
14         S.pop();
15     }
16 
17     int top() 
18     {
19         return S.top();    
20     }
21 
22     int getMin() 
23     {
24         return minS.top();    
25     }
26     
27 private:
28     stack<int> S;
29     stack<int> minS;
30 };

 

leetcode 155. Min Stack

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4209605.html

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