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

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

class MinStack {
    var main = Array()
    //计入push过的最小值
    var sub = Array()
    
    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!
    }
}


你可能感兴趣的:(面试题30. 包含min函数的栈)