zoukankan      html  css  js  c++  java
  • 12. Min Stack【medium】

    Implement a stack with min() function, which will return the smallest number in the stack.

    It should support push, pop and min operation all in O(1) cost.

     Notice

    min operation will never be called if there is no number in the stack.

    Example
    push(1)
    pop()   // return 1
    push(2)
    push(3)
    min()   // return 2
    push(1)
    min()   // return 1

    题意

    实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

    你实现的栈将支持pushpop 和 min 操作,所有操作要求都在O(1)时间内完成。

    解法一:

     1 class MinStack {
     2 public:
     3     stack<int> stk, minstk;
     4 
     5     MinStack() {
     6         // do intialization if necessary
     7         
     8     }
     9 
    10     /*
    11      * @param number: An integer
    12      * @return: nothing
    13      */
    14     void push(int number) {
    15         stk.push(number);
    16         if (minstk.empty() || number <= minstk.top()) {
    17             minstk.push(number);
    18         }
    19     }
    20 
    21     /*
    22      * @return: An integer
    23      */
    24     int pop() {
    25         int top = stk.top();
    26         stk.pop();
    27         if (top == minstk.top()) {
    28             minstk.pop();
    29         }
    30         return top;
    31     }
    32 
    33     /*
    34      * @return: An integer
    35      */
    36     int min() {
    37         return minstk.top();
    38     }
    39 };

    思路如下:

    1. 最小值有多个则都放到两个stack里, 尤其别忘放第二个;

    2. pop时若两个stack的最上面值相等则都pop, 不等则只pop第一个stack, 但是都得返回第一个stack的pop值;

    3. min时只返回第二个stack的peek值。 

    解法二:

     1 class MinStack {
     2 public:
     3     MinStack(){
     4         // do initialization if necessary
     5     }
     6 
     7     void push(int number) {
     8         s.push(number);
     9         m[number]++;
    10         it = m.begin();
    11     }
    12 
    13     int pop() {
    14         int res = s.top();
    15         s.pop();
    16 
    17         if (res == it->first) {
    18             (it->second)--;
    19             
    20             if (it->second == 0) {
    21                 m.erase(it);
    22                 it=m.begin();
    23             }
    24         } else {
    25             m.erase(res);
    26         }
    27 
    28         return res;
    29     }
    30 
    31     int min() {
    32         return it->first;
    33     }
    34 
    35 private:
    36     stack<int> s;
    37     map<int,int> m;
    38     map<int,int>::iterator it;
    39 };

    利用map的排序,参考@知之可否 的代码

  • 相关阅读:
    Thinking in Java
    Interview Common Sample Codes
    Longest Common Substring
    Mac键盘按键符号
    ElasticSearch
    Variables and Arithmetic Expression
    Associative Containers
    Container Adaptors
    string Type
    初识 tk.mybatis.mapper 通用mapper
  • 原文地址:https://www.cnblogs.com/abc-begin/p/8412848.html
Copyright © 2011-2022 走看看