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

【leetcode】155 - Min Stack

时间:2015-08-08 21:20:06      阅读:156      评论: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.

Solution:  若只维护一个栈stk,在每次getMin的时候检索stk需要两倍的临时空间,倒两次,故用两个栈,一个stk,一个min

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         stk.push(x);
 5         if(min.empty()||x<=min.top())min.push(x);       //if的两个判断条件顺序不能替换,否则stk添加第一个元素后getMin出错
 6     }
 7     void pop() {
 8         if(stk.top()==min.top()){
 9             stk.pop();
10             min.pop();
11         }else
12             stk.pop();
13     }
14     int top() {
15         return stk.top();
16     }
17     int getMin() {
18         return min.top();
19     }
20 private:
21     stack<int> stk;
22     stack<int> min;
23 };

 

【leetcode】155 - Min Stack

标签:

原文地址:http://www.cnblogs.com/irun/p/4713809.html

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