leetcode155-最小栈

原题

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) – 将元素 x 推入栈中。
  • pop() – 删除栈顶的元素。
  • top() – 获取栈顶元素。
  • getMin() – 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); –> 返回 -3.
minStack.pop();
minStack.top(); –> 返回 0.
minStack.getMin(); –> 返回 -2.

解法

思想

用list实现栈,再用一个stack保存着入栈期间出现过的所有最小数。(栈首元素表示在某个时刻list中最小的数)。

代码

class MinStack {
    public List<Integer> list;
    public Stack<Integer> stack;

    /** initialize your data structure here. */
    public MinStack() {
        list = new ArrayList<>();
        stack = new Stack<>();
    }

    public void push(int x) {
        //添加元素时,如果最小数栈是空的或者该元素比栈首元素要小,则入栈
        if(stack.empty()||x<=stack.peek()) stack.push(x);
        list.add(x);
    }

    public void pop() {
        //移除元素时,如果移除的元素是最小数栈的栈首元素,那么栈首元素也要出栈
        if(stack.peek().equals(list.get(list.size()-1)))
            stack.pop();
        list.remove(list.size()-1);
    }

    public int top() {
        return list.get(list.size()-1);
    }

    public int getMin() {
        //最小数栈的栈首元素
        return stack.peek();
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode155-%e6%9c%80%e5%b0%8f%e6%a0%88/

(0)
彭晨涛彭晨涛管理者
上一篇 2019年12月10日 18:05
下一篇 2019年12月12日 18:05

相关推荐

发表回复

登录后才能评论