12. 帶最小值操作的棧

實現一個帶有取最小值min方法的棧,min方法將返回當前棧中的最小值。

你實現的棧將支持pushpop 和 min 操作,所有操作要求都在O(1)時間內完成。

樣例

如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1


public class MinStack {
    
	Stack<Integer> main = new Stack();
	Stack<Integer> help = new Stack();
    
    public MinStack() {
        // do intialization if necessary
    }

    /*
     * @param number: An integer
     * @return: nothing
     */
    public void push(int number) {
        // write your code here
        main.push(number);
        if (!help.isEmpty()) {
			if (number <= help.peek()) {
				help.push(number);
			}
		} else {
			help.push(number);
		}
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
    	int data = 0;
    	if (!main.isEmpty()) {
			data = main.pop();
			if (data == help.peek()) {
				help.pop();
			}
		}
    	return data;
    	
    }

    /*
     * @return: An integer
     */
    public int min() {
        // write your code here
    	if (!help.isEmpty()) {
			return help.peek();
		} else {
			return -1;
		}
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章