zoukankan      html  css  js  c++  java
  • LeetCode 155. Min Stack

    原题链接在这里: https://leetcode.com/problems/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.

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.

    题解:

    可以用另一个stack, min_stk来维护最小值. push()时检测x是否小于等于min_stk 的peek(), 若true,则同时push进min_stk.

    pop()时若该值等于min_stk.peek()则同时对min_stk进行pop()操作。

    getMin()返回min_stk.peek()即可。

    Note:使用peek(), pop()之前,都要检测stack.isEmpty(), 否则会throw exception.

    Time Complexity: getMin(), O(1); push(), O(1); pop(), O(1); top(), O(1).

    Space: O(n).

    AC Java:

     1 public class MinStack {
     2 
     3     Stack<Integer> stk;
     4     Stack<Integer> minStk;
     5     public MinStack() {
     6         stk = new Stack<Integer>();
     7         minStk = new Stack<Integer>();
     8     }
     9     
    10     public void push(int x) {
    11         stk.push(x);
    12         if(minStk.isEmpty() || minStk.peek()>=x){
    13             minStk.push(x);
    14         }
    15     }
    16     
    17     public void pop() {
    18         if(!stk.isEmpty()){
    19             int x = stk.pop();
    20             if(!minStk.isEmpty() && x == minStk.peek()){
    21                 minStk.pop();
    22             }
    23         }
    24     }
    25     
    26     public int top() {
    27         if(!stk.isEmpty()){
    28             return stk.peek();
    29         }
    30         throw new IllegalStateException("Stack is empty!");
    31     }
    32     
    33     public int getMin() {
    34         if(!minStk.isEmpty()){
    35             return minStk.peek();
    36         }
    37         throw new IllegalStateException("Stack is empty!");
    38     }
    39 }
    40 
    41 /**
    42  * Your MinStack object will be instantiated and called as such:
    43  * MinStack obj = new MinStack();
    44  * obj.push(x);
    45  * obj.pop();
    46  * int param_3 = obj.top();
    47  * int param_4 = obj.getMin();
    48  */

    类似Max Stack.

  • 相关阅读:
    HTML5 meta最全使用手册
    CSS3实现开门动画
    angularJS学习资源最全汇总
    酷炫放大镜canvas实现
    完成评论功能
    从首页问答标题到问答详情页
    首页列表显示全部问答,完成问答详情页布局
    制作首页的显示列表。
    发布功能完成。
    登录之后更新导航
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825028.html
Copyright © 2011-2022 走看看