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 };

 

转载于:https://www.cnblogs.com/LUO77/p/5098818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值