Min Stack
问题:
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值
class MinStack { private Stack<Integer> normal = new Stack<Integer>(); private Stack<Integer> min = new Stack<Integer>(); public void push(int x) { if(min.isEmpty() || x <= min.peek()) { min.push(x); } normal.push(x); } public void pop() { int x = normal.pop(); if(x == min.peek()) { min.pop(); } } public int top() { return normal.peek(); } public int getMin() { return min.peek(); } }