Welcome to 发呆鱼.|

发呆鱼

园龄:3年4个月粉丝:1关注:0

leetcode刷题-剑指offer-30题

leetcode刷题-剑指offer-30题

题目

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

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

解答

class MinStack {

    Stack<Integer> stack1;
    Stack<Integer> stack2;

    /** initialize your data structure here. */
    public MinStack() {
        stack1=new Stack<Integer>();
        stack2=new Stack<Integer>();
    }

    public void push(int x) {
      stack1.push(x);
      if(stack2.isEmpty() || x<=stack2.peek()){
          stack2.push(x);
      }
    }

    public void pop() {
        int value=stack1.pop();
        if(stack2.peek()==value){
            stack2.pop();
        }
    }

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

    public int min() {
        return stack2.peek();
    }
}

本文作者:发呆鱼

本文链接:https://www.cnblogs.com/dyiblog/p/15778616.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   发呆鱼  阅读(22)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起