LeetCode 155. 最小棧 雙鏈表

LeetCode 155. 最小棧 雙鏈表

題目

	155. 最小棧
設計一個支持 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。

push(x) —— 將元素 x 推入棧中。
pop() —— 刪除棧頂的元素。
top() —— 獲取棧頂元素。
getMin() —— 檢索棧中的最小元素。
 

示例:

輸入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

輸出:
[null,null,null,null,-3,null,0,-2]

解釋:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
 

提示:

pop、top 和 getMin 操作總是在 非空棧 上調用。

思路

用鏈表模擬,記錄一個last指針以便加速,遇到刪除最小值的情況,就重新遍歷最小值,當然也可以用一個容器優化
到nlongn,懶得寫了

代碼

class MinStack {
	final node head;
	node last;
	int min = Integer.MAX_VALUE;
	static class node {
		int val;
		node next;
		node pre;
		public node(int val, node next, node pre) {
			this.val = val;
			this.next = next;
            this.pre=pre;
		}
	}

	public MinStack() {
		head = new node(Integer.MIN_VALUE, null, null);
		last = head;
	}

	public void push(int x) {
		last.next = new node(x, null, last);
		last = last.next;
		min = Math.min(x, min);

	}

	public void pop() {
        //確保頭節點不會被刪除
       if(last ==head )return ;
       //檢查刪除是否爲最小值
       if(last.val==min){
           min=Integer.MAX_VALUE;
           node tmp=head.next;
           while(tmp!=last){
               min=Math.min(tmp.val,min);
               tmp=tmp.next;
           }
       }
     
       //刪除尾節點操作
        last=last.pre;
        
        last.next=null;
        
        
        
	}
    public void printList(){
        node tmp=head.next;
        while(tmp!=null){
            System.out.print(tmp.val+" ");
            tmp=tmp.next;
            }
        System.out.println();
    }
	public int top() {
		return last.val;

	}

	public int getMin() {
		return min;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章