题目:设计一个栈结构,满足一下条件:min,push,pop操作的时间复杂度为O(1).
push和pop默认都比较好实现,min可以通过遍历试下,但是时间复杂度不符合要求,因为可以通过另外的栈存储最小值.
核心代码:
<pre><code>`class MinStack {
var stack:[Int] = []
var minStack:[Int] = []
func push(value:Int) {
stack.append(value)
let minValue:Int? = min()
if minValue == nil || value <= minValue! { // 与最小值相等的时候说明有重复数据
minStack.append(value)
}
}
func pop() {
if stack.count == 0 {
return
}
let value:Int = stack.last!
stack.removeLast()
if value == min() {
minStack.removeLast()
}
}
func min() -> Int? {
if minStack.count == 0 {
return nil
}
return minStack.last!
}
}`</code></pre>
测试代码:
<pre><code>`var minStack:MinStack = MinStack()
var minData:[Int] = [6, 5, 7, 3, 3, 8, 1, 10]
for i in 0..<minData.count {
minStack.push(value: minData[i])
}
for i in 0..<3 {
minStack.pop()
}
print("FlyElephant---minStack的数组-----(minStack.stack)---最小值--(minStack.minStack)")`</code></pre>
网友评论