标签:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
class MinStack { Stack<Integer> seqStack = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { int curMin; if(minStack.isEmpty()){ curMin = Integer.MAX_VALUE; } else{ curMin = minStack.peek(); } if(x <= curMin) minStack.push(x); seqStack.push(x); } public void pop() { if(seqStack.isEmpty()) return; else { int removedValue = seqStack.pop(); if(removedValue == minStack.peek()){ minStack.pop(); } } } public int top() { return seqStack.peek(); } public int getMin() { return minStack.peek(); } }
标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/44152799