zoukankan      html  css  js  c++  java
  • 155. 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.
    题目含义:设计一个最小栈,push, pop, top, 和 getMin 方法都是常量时间

     1 class MinStack {
     2 
     3    private Queue<Integer> p = new LinkedList<>();
     4     private Integer minValue = Integer.MAX_VALUE;
     5 
     6     /** Initialize your data structure here. */
     7     public MinStack() {
     8     }
     9 
    10     public int getMin() {
    11 
    12         for (int i=0;i<p.size();i++)
    13         {
    14             Integer value = p.poll();
    15             minValue = Math.min(minValue,value);
    16             p.add(value);
    17         }
    18         return minValue;
    19     }
    20 
    21     /** Push element x onto stack. */
    22     public void push(int x) {
    23         p.add(x);
    24         for (int i=1;i<p.size();i++)
    25         {
    26             p.add(p.poll());
    27         }
    28     }
    29 
    30     /** Removes the element on top of the stack and returns that element. */
    31     public int pop() {
    32         return p.poll();
    33     }
    34 
    35     /** Get the top element. */
    36     public int top() {
    37         return p.peek();
    38     }
    39 
    40     /** Returns whether the stack is empty. */
    41     public boolean empty() {
    42         return p.isEmpty();
    43     }
    44 }
  • 相关阅读:
    Codeforces Round 546 (Div. 2)
    Codeforces Round 545 (Div. 2)
    Codeforces Round 544(Div. 3)
    牛客小白月赛12
    Codeforces Round 261(Div. 2)
    Codeforces Round 260(Div. 2)
    Codeforces Round 259(Div. 2)
    Codeforces Round 258(Div. 2)
    Codeforces Round 257 (Div. 2)
    《A First Course in Probability》-chaper5-连续型随机变量-随机变量函数的分布
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7727491.html
Copyright © 2011-2022 走看看