[Swift]堆栈Stack:检索最小元素时间复杂度O(1)

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10062246.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。
 1 class MinStack {
 2     
 3     var stack: [Int]
 4     var minStack: [Int]
 5     
 6     /** initialize your data structure here. */
 7     init() {
 8         stack = []
 9         minStack = []
10     }
11     
12     func push(_ x: Int) {
13         stack.append(x)
14         if minStack.count == 0 {
15             minStack.append(x)
16         } else {
17             minStack.append(min(x, minStack[minStack.count - 1]))
18         }
19     }
20     
21     func pop() {
22         stack.removeLast()
23         minStack.removeLast()
24     }
25     
26     func top() -> Int {
27         return stack[stack.count - 1]
28     }
29     
30     func getMin() -> Int {
31         return minStack[minStack.count - 1]
32     }
33 }
34 
35 
36 /**
37  * Your MinStack object will be instantiated and called as such:
38  * let obj = MinStack()
39  * obj.push(x)
40  * obj.pop()
41  * let ret_3: Int = obj.top()
42  * let ret_4: Int = obj.getMin()
43  */
原文地址:https://www.cnblogs.com/strengthen/p/10062246.html