题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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.
提示:
各函数的调用总次数不超过 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()