-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem155.swift
38 lines (33 loc) · 891 Bytes
/
problem155.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
//ref: https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/
class MinStack {
private var stack: [Int]
private var minElement: Int
init() {
self.stack = [Int]()
self.minElement = Int.min
}
func push(_ x: Int) {
if stack.isEmpty {
stack.append(x)
minElement = x
} else if (x >= minElement) {
stack.append(x)
} else {
stack.append(2*x-minElement)
minElement = x
}
}
func pop() {
let tmp = stack.removeLast()
if (tmp < minElement) {
minElement = 2*minElement - tmp
}
}
func top() -> Int {
let tmp = stack.last!
return tmp >= minElement ? tmp : 2*minElement - tmp
}
func getMin() -> Int {
return minElement
}
}