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.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
原题链接:https://leetcode.com/problems/min-stack/description/
思路:
利用两个栈,一个存放数据data,一个存放当前栈的最小值min。每次数据栈data压入新数据x,都判断新数据x是不是当前最小,是的话,将x放入最小值栈min,不是的话,将min的顶部值再压入一次。每次data数据出栈,min也要出栈一个值,即最小值栈与数据栈保持同步更新。时间复杂度为O(1),用空间换时间。
class MinStack {
/** initialize your data structure here. */
public MinStack() {
}
private Stack <Integer> data = new Stack <Integer> ();
private Stack <Integer> min = new Stack <Integer> ();
public void push(int x) {
if (data.empty())
{
data.push(x);
min.push(x);
}
else
{
if(x < min.peek())
{
data.push(x);
min.push(x);
}
else
{
data.push(x);
min.push(min.peek());
}
}
}
public void pop() {
data.pop();
min.pop();
}
public int top() {
return data.peek();
}
public int getMin() {
return min.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
博主原创,未经博主允许,不得转载,谢谢~如果有错误请提醒我^-^