剑指 Offer 30. 包含min函数的栈
题目链接:https://leetcode.cn/problems/bao-han-minhan-shu-de-zhan-lcof/
题目说明:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
题解:详看注释
class MinStack {
/** initialize your data structure here. */
//用list来实现栈的功能
private List<Integer> stack=new LinkedList<>();
//minlist存储 stack元素为size个 时的最小值。即minlist.get(size-1)为当前的最小值
private List<Integer> minlist =new LinkedList<>();
//stack元素个数
private int size=0;
public MinStack() {
}
public void push(int x) {
//入栈
stack.add(x);
//保存此时的最小值
if(minlist.isEmpty()){
minlist.add(x);
}else{
minlist.add(Math.min(minlist.get(size-1),x));
}
//元素个数+1
size++;
}
public void pop() {
//出栈
stack.remove(size-1);
//最小值返回到上一个状态
minlist.remove(size-1);
//元素个数-1
size--;
}
public int top() {
return stack.get(size-1);
}
public int min() {
return minlist.get(size-1);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/