LeetCode刷题实战155:最小栈
共 2238字,需浏览 5分钟
·
2021-01-15 13:58
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.
题意
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
解题
public class MinStack {
private LinkedListstack;
Listarray;
int min;
public MinStack() {
stack = new LinkedList<>();
array = new ArrayList<>();
min = Integer.MAX_VALUE;
}
public void push(int x) {
stack.push(x);
array.add(x);
min = Math.min(min, x);
}
public void pop() {
int num = stack.pop();
array.remove(array.size() - 1);
if(array.size() > 0) {
min = array.get(0);
for (int i = 0; i < array.size(); i++) {
if(min > array.get(i)) {
min = array.get(i);
}
}
}else {
min = Integer.MAX_VALUE;
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}