特殊栈(可以获取最小值)

实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作.

【要求】

1.pop、push、getMin操作的时间复杂度都是O(1)。

2.设计的栈类型可以使用现成的栈结构。

解题思路:

使用两个栈结构,一个data栈一个min栈.data栈就是正常的栈操作,min栈在新加入元素时,新元素同栈顶的元素比较,谁小存谁.

比如数字[5,6,4,3,7]依次进行压栈操作,data栈中的结果就是[7,3,4,6,5],min栈中的结果就是[3,3,4,5,5].

public class GetMinStack {
    private Stack<Integer> data;
    private Stack<Integer> min;

    GetMinStack(Integer size){
        this.data = new Stack<Integer>();
        this.min = new Stack<Integer>();
    }

    public Integer peek(){
        return data.peek();
    }

    public void push(Integer i){
        this.data.push(i);
        if (!this.min.isEmpty()){
           if (this.getMin() > i){
               this.min.push(i);
           }else {
                this.min.push(this.getMin());
           }
        }
        this.min.push(i);
    }

    public Integer pop(){
        return data.pop();
    }

    public Integer getMin(){
        if (this.min.isEmpty()) {
            throw new RuntimeException("Your stack is empty.");
        }
        return this.min.peek();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39445556/article/details/104779528