題目
定義棧的數(shù)據(jù)結(jié)構(gòu)贸街,請在該類型中實現(xiàn)一個能夠得到棧的最小元素的 min 函數(shù)在該棧中,調(diào)用 min狸相、push 及 pop 的時間復(fù)雜度都是 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.
提示:
各函數(shù)的調(diào)用總次數(shù)不超過 20000 次
解題思路
class MinStack {
var stackList:[Int] = []
var minRecordList:[Int] = []
/** initialize your data structure here. */
init() {
}
func push(_ x: Int) {
stackList.append(x)
if minRecordList.isEmpty {
minRecordList.append(x)
return
}
// 通過棧方式登記最少值
if x < minRecordList.last! {
minRecordList.append(x)
}
else {
minRecordList.append(minRecordList.last!)
}
}
func pop() {
stackList.popLast()
minRecordList.popLast()
}
func top() -> Int {
return stackList.last!
}
func min() -> Int {
return minRecordList.last!
}
}
/**
* Your MinStack object will be instantiated and called as such:
* let obj = MinStack()
* obj.push(x)
* obj.pop()
* let ret_3: Int = obj.top()
* let ret_4: Int = obj.min()
*/
let obj = MinStack()
obj.push(5)
obj.push(4)
obj.pop()
let ret_3: Int = obj.top()
obj.push(3)
let ret_4: Int = obj.min()