zoukankan      html  css  js  c++  java
  • [leetcode 155]min stack

    1 题目

    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.

    2 思路

    前三个直接调用系统函数即可。c++之类还需要思考一下越界之类的问题。主要实现的是getMin(),要求在常数时间内实现,想了一下,没想出来,搜索,发现可以用空间换时间,新建个最小数的stack就可以了,要注意push时条件是等号。

    3 代码

        private Stack<Integer> stack = new Stack<Integer>();
        private Stack<Integer> min_stack = new Stack<Integer>();
        public void push(int x) {
            if (stack.isEmpty()) {
                min_stack.push(x);
            }else {
                if (x <= min_stack.peek()) {//小于等于
                    min_stack.push(x);
                }
            }
            stack.push(x);
        }
    
        public void pop() {
            int x = stack.pop();
           if (x == min_stack.peek()) {//相等
            min_stack.pop();
        } 
        }
    
        public int top() {
            return stack.peek();
        }
    
        public int getMin() {
            return min_stack.peek();
        }
  • 相关阅读:
    移动端测试知识概览
    24、CSS定位
    23、Xpath
    MySQL触发器
    MySQL存储过程和函数
    Cookie详解
    简单漏桶限流
    PHP异常和错误
    工厂方法模式
    简单工厂模式
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4288947.html
Copyright © 2011-2022 走看看