zoukankan      html  css  js  c++  java
  • Min Stack

    Description:

    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.

    Code:

     1 class MinStack {
     2 public:
     3     void push(int x) {
     4         m_stack.push(x);
     5         if (min_num.empty() || x<min_num.top())
     6            min_num.push(x);
     7         else
     8            min_num.push(min_num.top());
     9     }
    10 
    11     void pop() {
    12         assert( !m_stack.empty() && !min_num.empty() );
    13         m_stack.pop();
    14         min_num.pop();
    15     }
    16 
    17     int top() {
    18             assert( !m_stack.empty() );
    19             return m_stack.top();
    20     }
    21 
    22     int getMin() {
    23         return min_num.top();
    24     }
    25 private:
    26     stack<int>m_stack;
    27     stack<int>min_num;
    28 };
  • 相关阅读:
    POJ2352
    POJ 2524 并查集
    A POJ1611
    树状dp--B
    spring mvc实现文件上传与下载
    Joda-Time
    JAVA对象与JSON之间的转换
    jackson-databind注解
    JPA注解
    springMVC、spring、jpa、springData整合配置
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4592917.html
Copyright © 2011-2022 走看看