-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMinStack.kt
72 lines (60 loc) · 1.65 KB
/
MinStack.kt
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
60
61
62
63
64
65
66
67
68
69
70
71
72
package questions
import _utils.UseCommentAsDocumentation
import questions.common.ClassInvoker
import java.util.*
/**
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
* [Source](https://leetcode.com/problems/min-stack/)
*/
@UseCommentAsDocumentation
class MinStack {
private val array = mutableListOf<Int?>()
private val map = TreeMap<Int, MutableList<Int>>()
fun push(`val`: Int) {
array.add(`val`)
map[`val`] = map.getOrDefault(`val`, mutableListOf()).apply {
this.add(array.lastIndex)
}
}
fun pop() {
val lastIndex = array.lastIndex
val elem = array.removeAt(lastIndex)
val indices = map[elem]!!
indices.removeAt(indices.size - 1)
if (indices.isEmpty()) {
map.remove(elem)
}
}
fun top(): Int {
val lastIndex = array.lastIndex
return array[lastIndex]!!
}
fun getMin(): Int {
return map.firstKey()
}
fun print() {
println(array)
}
}
fun main() {
run {
val invoker = ClassInvoker<IntArray, Int>(
listOf(MinStack::class.java.simpleName, "push", "push", "push", "getMin", "pop", "top", "getMin")
) {
it.getOrNull(0)
}
invoker.invoke(
listOf(
intArrayOf(),
intArrayOf(-2),
intArrayOf(0),
intArrayOf(-3),
intArrayOf(),
intArrayOf(),
intArrayOf(),
intArrayOf()
),
listOf(null, null, null, null, -3, null, 0, -2)
)
}
}