Is there any other way to solve this without using PriorityQueue? One could use a list and sort it always everytime a new non-zero value is created from smashing the rocks together but that won’t be that much different than using PriorityQueue which sorts the elements in every offer
import java.util.*
import kotlin.Comparator
class Solution {
fun lastStoneWeight(stones: IntArray): Int {
var map = PriorityQueue(stones.size, Comparator<Int> { a, b ->
when {
a < b -> 1
a == b -> 0
else -> -1
}
})
stones.forEach { map.offer(it) }
while(!map.isEmpty()) {
if(map.size == 1) break
val y = map.poll()
val x = map.poll()
val diff = when {
x == y -> 0
else -> y - x
}
map.offer(diff)
}
return map.first()
}
}
Runtime: 136 ms, faster than 96.88% of Kotlin online submissions for Last Stone Weight.
Memory Usage: 32.3 MB, less than 100.00% of Kotlin online submissions for Last Stone Weight.