• 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();
        }
    }




  • 相关阅读:
    吃透空洞卷积(Dilated Convolutions)
    CondInst:性能和速度均超越Mask RCNN的实例分割模型
    图像处理基础:颜色空间及其OpenCV实现
    caffe模型转rknn模型的方法
    探索 YOLO v3 源码
    探索 YOLO v3 源码
    事件
    组合,模板,bolck块
    WXSS学习
    其他组件
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/de52b1cfc3c013858c635bafd7423fd1.html
Copyright © 2020-2023  润新知