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 }
  • 相关阅读:
    js 点击复制内容
    tp5 日志的用途以及简单使用
    iOS UIKit:TableView之表格创建(1)
    Linux平台的boost安装全解
    iOS UIKit:CollectionView之布局(2)
    iOS UIKit:CollectionView之设计 (1)
    iOS 网络编程:socket
    Objective-C:内存管理
    iOS UIKit:TabBar Controller
    iOS UIKit:Navigation Controllers
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7727491.html
Copyright © 2011-2022 走看看