zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    PAT(A) 1065. A+B and C (64bit) (20)
    PAT(A) 1046. Shortest Distance (20)
    PAT(A) 1042. Shuffling Machine (20)
    PAT(A) 1009. Product of Polynomials (25)
    PAT(A) 1002. A+B for Polynomials (25)
    win10开始菜单打不开怎么办?
    排序
    C语言文件读写操作总结
    NO.3 4 章 模拟、算法初步
    POJ2104 K-th Number(归并树)
  • 原文地址:https://www.cnblogs.com/LUO77/p/5098818.html
Copyright © 2011-2022 走看看