面试题30. 包含min函数的栈

2020-03-27  本文已影响0人  寂灭天骄小童鞋

https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/submissions/

class MinStack {
    var main = Array<Int>()
    //计入push过的最小值
    var sub = Array<Int>()
    
    init() {
        
    }
    
    func push(_ x: Int) {
        main.append(x)
        if sub.isEmpty || sub.last! >= x{
            sub.append(x)
        }
    }
    
    func pop() {
        if main.last! == sub.last! {
            sub.removeLast()
        }
        main.removeLast()
    }
    
    func top() -> Int {
        return main.last!
    }
    
    func min() -> Int {
        return sub.last!
    }
}


上一篇 下一篇

猜你喜欢

热点阅读