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 { private Stack<Integer> stack = new Stack<Integer>(); private Stack<Integer> ministack = new Stack<Integer>(); public void push(int x) { stack.push(x); if (ministack.empty()) { ministack.push(x); } else if (ministack.peek() < x) { ministack.push(ministack.peek()); } else { ministack.push(x); } } public void pop() { ministack.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return ministack.peek(); } }
没有评论:
发表评论