標籤:
Question:
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.
1、題型分類:
2、思路:
這道題需要實現一個能夠擷取最小值的棧,可以想到的必然是要麼每次通過遍曆擷取,要麼空間換時間,建立一個資料結構儲存這些有序最小值。剛開始一直沒有想過用Stack去實現這個功能,想到的是利用List去進行有序儲存,但是這樣每次插入的時間複雜度都不低,另外還有刪除操作,沒法實現題目的要求。現在希望一個資料結構,資料有序且從頂至下由小到大且能夠包含所有的元素,這樣就能夠與Stack並行操作了,但是實現想不出來這樣的結構。再去考慮這道題目的關鍵,getMin擷取最小值,但不需要刪除,那麼我們可以儲存插入進來的小於當前最小值的數值,,而且這個順序還必須和Stack裡面數的順序一致,那麼最後還是需要使用Stack,問題來了,刪除怎麼辦?由於順序一致,只要兩個棧頂部資料相同就刪除。如:
3、時間複雜度:
4、代碼:
class MinStack { Stack<Integer> stack=new Stack<Integer>(); Stack<Integer> minStack=new Stack<Integer>(); public void push(int x) { stack.push(x); if(minStack.isEmpty() || (!minStack.isEmpty() && x<=minStack.peek())) minStack.push(x); } public void pop() { if(!stack.isEmpty()) { if(!minStack.isEmpty() && minStack.peek().intValue()==stack.peek().intValue()) minStack.pop(); stack.pop(); } } public int top() { return stack.peek(); } public int getMin() { if(!minStack.isEmpty()) return minStack.peek(); return 0; }}
5、最佳化:
6、擴充:
[LeetCode] Min Stack