zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    分析:用两个栈来实现

     1 class MinStack {
     2     // normal stack
     3     Stack<Integer> st = new Stack<Integer>();
     4     // min value stack
     5     Stack<Integer> stm = new Stack<Integer>();
     6     
     7     public void push(int x) {
     8         st.push(x);
     9         if (stm.isEmpty() || stm.peek() >= x)
    10             stm.push(x);
    11     }
    12 
    13     public void pop() {
    14         int peek = st.peek();
    15         st.pop();
    16         if (peek <= stm.peek())
    17             stm.pop();
    18     }
    19 
    20     public int top() {
    21         return st.peek();
    22     }
    23 
    24     public int getMin() {
    25         return stm.peek();
    26     }
    27 }
  • 相关阅读:
    type和object详解
    元类+单例
    单表查询和多表查询
    外键
    存储引擎,MySQL中的数据类型及约束
    壹拾壹




  • 原文地址:https://www.cnblogs.com/tonyhu1993/p/4945337.html
Copyright © 2011-2022 走看看