zoukankan      html  css  js  c++  java
  • Min Stack

    Implement a stack with min() function, which will return the smallest number in the stack.

    It should support push, pop and min operation all in O(1) cost.

     Notice

    min operation will never be called if there is no number in the stack.

    分析

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    public class MinStack {
        private Stack<Integer> stack = new Stack<Integer>();
        private Stack<Integer> stack_min = new Stack<Integer>();
         
        public MinStack() {
            // do initialize if necessary
        }
         
        public void push(int number) {
            // write your code here
            stack.push(number);
            if(!stack_min.empty() && stack_min.peek() < number){
                stack_min.push(stack_min.peek());
            }
            else{
                stack_min.push(number);
            }
        }
     
        public int pop() {
            // write your code here
            int top = -1;
            if(!stack.empty()){
                top = stack.peek();
                stack.pop();
                stack_min.pop();
            }
            return top;
        }
     
        public int min() {
            // write your code here
            return stack_min.empty() ? -1 : stack_min.peek();
        }
    }




  • 相关阅读:
    进程间通信:命名管道FIFO(2)
    进程间通信:管道(1)
    POSIX线程学习
    进程与信号学习
    堆栈的区别与联系
    浅读《构建之法:现代软件工程》有感
    CSS学习成长记
    jquery学习成长记(一)
    html学习成长记
    Razor视图
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/de52b1cfc3c013858c635bafd7423fd1.html
Copyright © 2011-2022 走看看