풀이
import java.util.*
/*
* 2020-11-07
* https://programmers.co.kr/learn/courses/30/lessons/42628
*/
fun solveDoublePriorityQueue(operations: Array<String>): IntArray {
val minQueue = PriorityQueue<Int> { n1, n2 -> n1 - n2 }
val maxQueue = PriorityQueue<Int> { n1, n2 -> n2 - n1 }
operations.forEach {
val (arg, numStr) = it.split(" ")
val num = numStr.toInt()
if (arg == "I") {
minQueue.add(num)
maxQueue.add(num)
}
if (arg == "D") {
if (num == 1) {
val max = maxQueue.poll()
minQueue.remove(max)
}
if (num == -1) {
val min = minQueue.poll()
maxQueue.remove(min)
}
}
}
return if (minQueue.count() == 0) {
intArrayOf(0, 0)
} else {
intArrayOf(maxQueue.poll(), minQueue.poll())
}
}
테스트
class HeapTest {
companion object {
@JvmStatic
fun doublePriorityQueueArgs(): Stream<Arguments> = Stream.of(
Arguments.of(arrayOf("I 16", "D 1"), intArrayOf(0, 0)),
Arguments.of(arrayOf("I 7", "I 5", "I -5", "D -1"), intArrayOf(7, 5))
)
}
@ParameterizedTest
@MethodSource("doublePriorityQueueArgs")
fun testDoublePriorityQueue(operations: Array<String>, expected: IntArray) {
val result = solveDoublePriorityQueue(operations)
assertEquals(expected[0], result[0])
assertEquals(expected[1], result[1])
}
}