LeetCode 腾讯精选50题--最小栈

题目很简单,实现一个最小栈,能够以线形的时间获取栈中元素的最小值

自己的思路如下:

利用数组,以及两个变量, last用于记录栈顶元素的位置,min用于记录栈中元素的最小值;

每一次push,都比较min与x的大小,其次,push操作执行时若数组已满,这需要进行扩容,将数组长度扩大为原来的两倍,并进行数组的迁移。每一次 pop 时,若删除的是最小元素,则遍历数组重新找到最小的元素,然后删除栈顶元素。

时间分析:

push: 最坏情况为O(n),其余为O(1)

pop:最坏情况:O(n),其余为O(1)

top:O(1)

getMin: O(1)

以下是代码:

private int[] array;

    private int last;

    private int min;

    public MinStack() {
        array = new int[16];
        last=0;
        min = 0;
    }

    public void push(int x) {
        if(last >= array.length){
            this.array = expand(this.array);
        }
        array[last++] = x;
        if(min > x || last==1){
            this.min = x;
        }
    }

    public void pop() {
        if(last -1 <0){
            return;
        }
        if(this.min == array[last-1]){
            this.min = findMin(array,last-1);
        }
        this.last = this.last - 1;

        this.last = this.last < 0 ? 0:this.last;
    }

    public int top() {

        if(last -1 <0){
            return 0;
        }

        int result = this.array[last-1];

        return result;
    }

    public int getMin() {
        return this.min;
    }

    private int[] expand(int[] array){

        int[] tempArray = new int[array.length*2];
        for (int i=0;i<array.length;i++){
            tempArray[i] = array[i];
        }

        return tempArray;
    }

    private int findMin(int array[],int last){

        if(last <=0){
            return 0;
        }
        int tempMin = array[last-1];
        for (int i=last-1;i>=0;i--){
            tempMin = Math.min(array[i],tempMin);
        }
        return tempMin;

    }
扫描二维码关注公众号,回复: 6941708 查看本文章

猜你喜欢

转载自www.cnblogs.com/Kaithy-Rookie/p/11296064.html