題目
定義棧的數據結構,請在該類型中實現一個能夠得到棧的最小元素的 min 函數在該棧中,調用 min、push 及 pop 的時間複雜度都是 O(1)。
代碼
Python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
# A數據棧,B輔助存儲最小值棧
self.A, self.B = [], []
def push(self, x: int) -> None:
self.A.append(x)
# B爲空/B棧頂元素大於等於壓入元素
if not self.B or self.B[-1]>=x:
self.B.append(x)
def pop(self) -> None:
# 彈出元素恰好是最小值
if self.A.pop()==self.B[-1]:
self.B.pop()
def top(self) -> int:
return self.A[-1]
def min(self) -> int:
return self.B[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()
C++
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
// A數據棧,B輔助棧
stack<int> A;
stack<int> B;
void push(int x) {
A.push(x);
// 注意兩個條件分開寫,保持出棧一致性
if (B.empty()) {
B.push(x);
}
else if (B.top() >= x) {
B.push(x);
}
}
void pop() {
if (!A.empty()) {
if (A.top()==B.top()) B.pop();
A.pop();
}
}
int top() {
return A.top();
}
int min() {
return B.top();
}
};
/**
* 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();
*/