题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| import Foundation
class For21Solution { var stack: Array<Int> var min: Int init() { self.stack = [Int]() self.min = Int.max } func push(_ n: Int) { if n < min { min = n } self.stack.append(n) self.stack.append(min) } func pop() -> Int { if self.stack.count == 0 { print("stack.count==0") return 0 } self.stack.popLast() min = self.stack.last! return self.stack.popLast()! } func getMin() -> Int { if self.stack.count == 0 { print("stack.count==0") return 0 } return self.stack.last! } }
|
算法思想:利用数组模拟一个栈。
github地址:https://github.com/cubegao/LeetCode