LeetCode155-最小栈
题目
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
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.
解法
使用数组和栈存放对应的数据。栈存放一个一维数组,数组长度为2。第一个数放当前push进去的数,第二个数放当前最小值。
class MinStack {
private Stack<int[]> st ;
/** initialize your data structure here. */
public MinStack() {
st = new Stack<>();
}
public void push(int x) {
if(st.isEmpty()){
st.push(new int[]{x,x});
}
else{
st.push(new int[]{x,Math.min(x,st.peek()[1])});
}
}
public void pop() {
st.pop();
}
public int top() {
return st.peek()[0];
}
public int getMin() {
return st.peek()[1];
}
}