Skip to content

Instantly share code, notes, and snippets.

@omo

omo/Solution.kt Secret

Created August 2, 2022 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omo/866be446908411c327ebeac4cba0b1e7 to your computer and use it in GitHub Desktop.
Save omo/866be446908411c327ebeac4cba0b1e7 to your computer and use it in GitHub Desktop.
import java.util.PriorityQueue
class Solution {
data class Entry(val row: Int, val col: Int, val num: Int)
fun kthSmallest(matrix: Array<IntArray>, k: Int): Int {
val q = PriorityQueue<Entry>(1, { x, y -> x.num - y.num })
matrix.forEachIndexed{ i, row -> q.add(Entry(i, 0, row.get(0))) }
var nth: Int = 0
var nthMin: Int = Int.MIN_VALUE
while (!q.isEmpty()) {
val e = q.poll()
nth++
nthMin = e.num
if (nth == k) {
return nthMin
}
if (e.col + 1 < matrix.size) {
val r = e.row
val c = e.col + 1
q.add(Entry(r, c, matrix[r][c]))
}
}
return nthMin
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment