题目
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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.
Swift
//包含min函数的栈
class MinStack {
var listStack:[Int] = [Int]()
var minListStack:[Int] = [Int]()
/** initialize your data structure here. */
init() {
}
func push(_ x: Int) {
listStack.append(x)
if let currentMinValue = minListStack.last {
if x < currentMinValue {
minListStack.append(x)
} else {
minListStack.append(currentMinValue)
}
} else {
minListStack.append(x)
}
}
func pop() {
if listStack.isEmpty == false && minListStack.isEmpty == false {
listStack.removeLast()
minListStack.removeLast()
} else {
//异常处理(两个数组个数不相等的情况处理)
if listStack.isEmpty == false {
listStack.removeAll()
}
if minListStack.isEmpty == false {
minListStack.removeAll()
}
}
}
func top() -> Int {
if let tempTop = listStack.last {
return tempTop
}
return -1;
}
func min() -> Int {
if let tempTop = minListStack.last {
return tempTop
}
return -1;
}
}
var minStack = MinStack()
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min();
minStack.pop();
minStack.top();
minStack.min();
Java
待更新
网友评论