zoukankan      html  css  js  c++  java
  • LeetCode题解 #155 Min Stack

    写一个栈,支持push pop top getMin

    难就难在在要在常量时间内返回最小的元素。

    一开始乱想了很多东西,想到了HashMap,treeMap,堆什么的,都被自己一一否决了。

    后来想到其实用一个栈来记录当前的最小值就好了,只有当被删除的元素等于min栈的栈顶元素时,才删除min栈里面的元素。

    min栈中每个元素代表着那一段栈中的最小值了。

    // stack: store the stack numbers
    private Stack<Integer> stack = new Stack<Integer>();
    // minStack: store the current min values
    private Stack<Integer> minStack = new Stack<Integer>();

    public void push(int x) {
    // store current min value into minStack
    if (minStack.isEmpty() || x <= minStack.peek())
    minStack.push(x);
    stack.push(x);
    }

    public void pop() {
    // use equals to compare the value of two object, if equal, pop both of them
    if (stack.peek().equals(minStack.peek()))
    minStack.pop();
    stack.pop();
    }

    public int top() {
    return stack.peek();
    }

    public int getMin() {
    return minStack.peek();
    }

  • 相关阅读:
    1.Go环境安装
    IDEA启动Tomcat控制台中文显示乱码
    专注的含义
    翻出一封古老的信
    若有所思
    B+Tree与B-Tree 的区别
    Redis集群 什么是slots
    夜深人静,听雨
    随心所想
    本性可以改吗
  • 原文地址:https://www.cnblogs.com/wzben/p/5018091.html
Copyright © 2011-2022 走看看