zoukankan      html  css  js  c++  java
  • LeetCode

    Min Stack

    2015.1.23 12:13

    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:

      This could almost be counted as a FAQ. You'll find a same question in "Cracking the Coding Interview". A min stack is maintained alongside the data stack, recording every minimal (so far) element. The min stack is updated whever a new minimal value is being pushed, or the current minimal value is being popped.

      Total time complexity for each operation is strictly O(1). Extra space of O(n) is required to maintain the min stack.

    Accepted code:

     1 // 1AC, old
     2 #include <stack>
     3 using namespace std;
     4 
     5 class MinStack {
     6 public:
     7     void push(int x) {
     8         if (ms.empty() || ms.top() >= x) {
     9             ms.push(x);
    10         }
    11         s.push(x);
    12     }
    13 
    14     void pop() {
    15         if (s.top() == ms.top()) {
    16             ms.pop();
    17         }
    18         s.pop();
    19     }
    20 
    21     int top() {
    22         return s.top();
    23     }
    24 
    25     int getMin() {
    26         return ms.top();
    27     }
    28 private:
    29     stack<int> s, ms;
    30 };
  • 相关阅读:
    Eclipse Plugin for Hadoop
    Hadoop伪分布模式配置
    Hadoop单机模式配置
    20180711-Java Number类
    20180711-Java分支结构 – if…else/switch
    20180709-Java循环结构
    20180708-Java运算符
    20180708-Java修饰符
    20180708-Java变量类型
    20180705-Java对象和类
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/4243876.html
Copyright © 2011-2022 走看看