leetcode 155. Min Stack

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.

 

 

主要是这个getMin函数,这道题我是用vector实现的。

很容易time exceeded,因为测试用例是很多的,而且又有2,147,483,647这样的边界数,真的是很讨厌。

我发现像这种要求时间的,都可以用增量思想来做,就是每一步所得到的结果都能为最终结果有所贡献的。

 

就拿这道题来说吧,我们可以每次暂存最小的数,在push的时候比较是否更小,如果更小,就更新当前最小的数。

不过我忽略了一个问题,就是假如pop了最小的数的话,怎么办?

所以在pop的时候,我们要判断是否将最小的数已经删除,如果删除,就需要遍历一遍当前的minstack来重新获取,这样的次数不多,因此不会太大影响时间。

 

 1 class MinStack {
 2 public:
 3     vector<int> sta1;
 4     int conMin;
 5     void push(int x) {
 6         if(sta1.empty()) conMin=x;
 7         else if(x<conMin) conMin=x;
 8         sta1.push_back(x);
 9     }
10 
11     void pop() {
12         int x=sta1.back();
13         sta1.pop_back();
14         if(x==conMin){
15             conMin=2147483647 ;
16             for(int i=0;i<sta1.size();i++){
17                 if(sta1[i]<conMin) conMin=sta1[i];
18             }
19         }
20         
21     }
22 
23     int top() {
24         int x=sta1.back();
25         return x;
26     }
27 
28     int getMin() {
29         return conMin;
30     }
31 };

 

posted @ 2016-01-04 14:24  0giant  阅读(180)  评论(0编辑  收藏  举报