Min Stack
Total Accepted: 28489 Total Submissions: 160974My Submissions
Question Solution
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.
分析,我使用双向链表,把栈中值按大小关系,连接起来
class MinStack {
element Head=new element(0);
List<element> stack=new ArrayList<element>();
int top=0;
public void push(int x) {
element y=new element(x);
top++;
stack.add(y);
element z=Head;
while(z.next!=null&&x>z.next.x)
{
z=z.next;
}
if(z.next==null)
{
z.next=y;
y.last=z;
}
else
{
y.next=z.next;
z.next=y;
y.next.last=y;
y.last=z;
}
}
public void pop() {
top--;
if(stack.get(top).next!=null)
{
stack.get(top).next.last=stack.get(top).last;
stack.get(top).last.next=stack.get(top).next;
}
else
{
stack.get(top).last.next=stack.get(top).next;
}
stack.remove(top);
}
public int top() {
return stack.get(top-1).x;
}
public int getMin() {
return Head.next.x;
}
}
class element{
int x;
element next;
element last;
element(int p){
x=p;
next=null;
last=null;
}
}
Submission Result: Time Limit Exceeded
这道题的关键之处就在于 minStack 的设计,push() pop() top() 这些操作Java内置的Stack都有,不必多说。
我最初想着再弄两个数组,分别记录每个元素的前一个比它大的和后一个比它小的,想复杂了。
第一次看上面的代码,还觉得它有问题,为啥只在 x<minStack.peek() 时压栈?如果,push(5), push(1), push(3) 这样minStack里不就只有5和1,这样pop()出1后, getMin() 不就得到5而不是3吗?其实这样想是错的,因为要想pop()出1之前,3就已经被pop()出了。.
minStack 记录的永远是当前所有元素中最小的,无论 minStack.peek() 在stack 中所处的位置。
class MinStack {
// stack: store the stack numbers
private Stack<Integer> stack = new Stack<Integer>();
// minStack: store the current min values
private Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
// store current min value into minStack
if (minStack.isEmpty() || x <= minStack.peek())
minStack.push(x);
stack.push(x);
}
public void pop() {
// use equals to compare the value of two object, if equal, pop both of them
if (stack.peek().equals(minStack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}