定義棧的數據結構,請在該類型中實現一個能夠得到棧的最小元素的 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.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class MinStack {
/** initialize your data structure here. */
Stack<Integer> s = new Stack<>();Stack<Integer> min = new Stack<>();
public MinStack() {
}
public void push(int x) {
s.push(x);
if(min.isEmpty()||min.peek()>=x) {
min.push(x);
}else{
min.push(min.peek());
}
}
public void pop() {
s.pop();
min.pop();
}
public int top() {
return s.peek();
}
public int min() {
return min.peek();
}
}
/**
* 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();
*/