標籤:
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.
解題思路:
比較直觀。用一個min stack專門存放最小值,如果有比它小或是相等的(有多個平行的最小值都要單獨存放,否則pop後會出問題),
則存放其到minstack.
Java code:
class MinStack { Stack<Integer> elements = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { elements.push(x); if(minStack.isEmpty() || x <= minStack.peek()){ minStack.push(x); } } public void pop() { if(elements.isEmpty()){ return; } if((int)elements.peek() == (int)(minStack.peek())){ minStack.pop(); } elements.pop(); } public int top() { return elements.peek(); } public int getMin() { return minStack.peek(); }}
Reference:
1. http://www.cnblogs.com/yuzhangcmu/p/4106783.html
Leetcode Min Stack