数据结构与算法(Java) 19:特殊栈

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

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

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

思路 设置两个栈,一个(data)用于正常使用,另一个(min)用于“实时”记录当前栈中元素最小值。若data入栈,min也入栈【min中的值入栈时取:当前栈顶元素和待入栈值,二者中的最小值】;若data出栈,min也取出栈顶元素。保持同步。

package algorithm.section3;

public class NewStack {
    private Integer[] data;
    private Integer[] min;
    private Integer size;

    public NewStack(int initialSize){
        if (initialSize < 0)
            throw new IllegalArgumentException("The init size is less than 0!");
        data = new Integer[initialSize];
        min = new Integer[initialSize];
        size = 0;
    }

    public void push(Integer obj){
        if (size == data.length) throw new IndexOutOfBoundsException("The stack is full!");
        if (size == 0){
            data[size] = obj;
            min[size] = obj;
            size++;
            return;
        }
        data[size] = obj;
        min[size] = Math.min(obj, min[size - 1]);
        size++;
    }

    public Integer peek(){
        if (size == 0) return null;
        return data[size - 1];
    }

    public Integer pop(){
        if (size == 0) throw new IndexOutOfBoundsException("The stack is empty");
        return data[--size];
    }

    public Integer getMin(){
        if (size == 0) return null;
        return min[size - 1];
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105590361