题目链接:https://leetcode.com/problems/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.
解题思路:
这题希望我们在常量时间内找出栈中的最小值。
方法是用空间换时间的做法。
1. 建立两个栈,一个是正常放置元素的栈 a,另一个是存放当前栈 a 中最小元素的栈 b
2. 栈 a 每次入栈一个元素,都要和栈 b 的栈顶元素做比较
3. 如果入栈元素小于栈 b 栈顶元素,那么该入栈元素就是栈 a 当前最小的元素,应把该元素压入栈 b
4. 否则,若当前入栈元素大于栈 b 栈顶元素,说明栈 b 的栈顶元素依然是当前栈 a 中最小的元素,用 peek 方法获取栈 b 栈顶元素后再压入栈 b
5. 弹栈时,栈 a 和栈 b 都弹出栈顶元素
注意:当把 LinkedList 当做栈时,也就是添加元素使用 push() 方法时,栈顶元素相当于链表的表头,栈底元素相当于链表末尾。故,取栈顶元素用方法 peek()。
代码实现:
class MinStack {
private LinkedList<Integer> stack = new LinkedList();
private LinkedList<Integer> min = new LinkedList();
public void push(int x) {
stack.push(x);
if(min.isEmpty()) {
min.push(x);
} else {
int minX = min.peek();
if(minX > x)
min.push(x);
else
min.push(minX);
}
}
public void pop() {
stack.pop();
min.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min.peek();
}
}
17 / 17 test cases passed.
Status: Accepted
Runtime: 10 ms