zoukankan      html  css  js  c++  java
  • Min Stack

    1. Title

    Min Stack

    2. Http address

    https://leetcode.com/problems/min-stack/

     1 import java.util.*;
     2 public class MinStack {
     3 
     4     // Accepted 
     5     public LinkedList<Integer> stack = new LinkedList<Integer>();
     6     public LinkedList<Integer> min_stack = new LinkedList<Integer>();
     7     
     8       public void push(int x) {
     9           
    10               stack.offerFirst(x);
    11               
    12               if ( min_stack.isEmpty() || x < min_stack.peekFirst()) {
    13                   min_stack.offerFirst(x);
    14               }else{
    15                   min_stack.offerFirst(min_stack.peekFirst());
    16               }
    17       }
    18 
    19      public void pop() {
    20             stack.pollFirst();
    21             min_stack.pollFirst();
    22      }
    23 
    24         public int top() {
    25             return stack.peekFirst();
    26         }
    27 
    28         public int getMin() {
    29                 return min_stack.peekFirst();
    30         }
    31 }

    3. The question

    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.

    4. My code(AC)

  • 相关阅读:
    Code::blocks 使用c++ long double类型出错
    数论四大定理
    线性基
    win7 下强制删除文件
    C++数组指针的引用
    学习方法
    MySQL的ON DUPLICATE KEY UPDATE用法
    MVCC
    RabbitMQ中的Connection 和 Channel
    myisam和innodb的比较
  • 原文地址:https://www.cnblogs.com/ordili/p/4928528.html
Copyright © 2011-2022 走看看