Min Stack

来源:互联网 发布:天谕发色数据明珠 编辑:程序博客网 时间:2024/05/23 19:23

每日一题;

今天写的是最小栈,感觉很简单,但是好多细节不容忽视呀!需要注意的地方:

1、有时间还是继续看看源码吧;

2、首先需要考虑越界的问题,需要数组扩容;但是初始值定义的大小很重要,两张图说明问题:

第一张是数组初始大小为100的,花费时间429ms;

第二章是数组初始大小为10000的,花费时间是492ms;

3、取最小值的时候,第一次做的时候是没取一次,遍历一次,结果超时了,5000+ms吧~现在每次都记录最小值,弹出的时候判断要弹出的值和最小值相等的时候再遍历取值,时间果断降了下来。


Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
class MinStack {    private int[] values;    private int high = -1;    private int number = 100;    private int min = Integer.MAX_VALUE;    public MinStack(){        values = new int[number];    }    public void push(int x) {        high++;        if(high>=number){            number += number/2;            values = Arrays.copyOfRange(values,0,number);        }        values[high] = x;        if(x<min){            min = x;        }    }    public void pop() {        if(high < 0){            return;        }        if(values[high] == min){            findMin();        }        high--;    }    public int top() {        if(high < 0){            return -1;        }        return values[high];    }    public int getMin() {        return min;    }    private void findMin(){        min = Integer.MAX_VALUE;        for(int i = 0;i<high;i++){            if(values[i]<min)                min = values[i];        }    }}


0 0
原创粉丝点击