码迷,mamicode.com
首页 > 其他好文 > 详细

实现一个特殊的栈,要求push,poll , getMin方法时间复杂度都是O(N)

时间:2019-10-06 15:16:25      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:cep   return   bsp   sem   size   特殊   font   throw   run   

借助两个栈来实现

public class GetMinStack {

    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;

    public GetMinStack() {
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }

    public void push(int obj) {
        if (stackMin.isEmpty()) {
            stackMin.push(obj);
        } else {
            stackMin.push(obj < getmin() ? obj : getmin());
        }
        stackData.push(obj);
    }

    public int getmin() {
        if (stackMin.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        return stackMin.peek();
    }

    public int pop() {
        if (this.stackData.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        this.stackMin.pop();
        return this.stackData.pop();
    }

}

 

实现一个特殊的栈,要求push,poll , getMin方法时间复杂度都是O(N)

标签:cep   return   bsp   sem   size   特殊   font   throw   run   

原文地址:https://www.cnblogs.com/moris5013/p/11627223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!