-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathAprilSolDay10.swift
59 lines (49 loc) · 1.31 KB
/
AprilSolDay10.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
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// AprilSolDay10.swift
// LeetCodeChallenge
//
// Created by Michael Ho on 4/15/20.
// Copyright © 2020 Michael Ho. All rights reserved.
//
// LeetCode: https://leetcode.com/problems/min-stack/
class AprilSolDay10 {
class MinStack: MinStackProtocol {
var stack: [Node]
/** initialize your data structure here. */
init() {
stack = [Node]()
}
func push(_ x: Int) {
stack.append(Node(x, min(x, getMin())))
}
func pop() {
stack.removeLast()
}
func top() -> Int {
guard let last = stack.last else { return -1 }
return last.val
}
func getMin() -> Int {
guard let last = stack.last else { return Int.max }
return last.minVal
}
}
class Node {
var val: Int
var minVal: Int
init(_ value: Int, _ minVal: Int) {
self.val = value
self.minVal = minVal
}
}
}
protocol MinStackProtocol {
// Push element x onto stack.
func push(_ x: Int)
// Removes the element on top of the stack.
func pop()
// Get the top element.
func top() -> Int
// Retrieve the minimum element in the stack.
func getMin() -> Int
}