forked from NilaakashSingh/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinStack.swift
46 lines (37 loc) · 1.08 KB
/
MinStack.swift
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
40
41
42
43
44
45
46
/**
* Question Link: https://leetcode.com/problems/min-stack/
* Primary idea: Use a helper stack to help save the minimum values --
* only when the new pushed value is less than the top value,
* and remove values correspond to pop operation
* Time Complexity: O(1), Space Complexity: O(n)
*/
class MinStack {
var stack: [Int]
var minStack: [Int]
/** initialize your data structure here. */
init() {
stack = [Int]()
minStack = [Int]()
}
func push(_ x: Int) {
stack.append(x)
if minStack.isEmpty || x <= minStack.last! {
minStack.append(x)
}
}
func pop() {
guard !stack.isEmpty else {
return
}
let removedVal = stack.removeLast()
if let last = minStack.last, last == removedVal {
minStack.removeLast()
}
}
func top() -> Int {
return stack.isEmpty ? -1 : stack.last!
}
func getMin() -> Int {
return minStack.isEmpty ? -1 : minStack.last!
}
}