Skip to content

Commit eb49cd3

Browse files
committed
- Add: Kth Smallest Element in a Sorted Matrix
1 parent 2680c32 commit eb49cd3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
fun kthSmallest(m: Array<IntArray>, kth: Int): Int {
3+
val size = m.size
4+
val pq = PriorityQueue<Pair<Int, Int>>( compareBy { m[it.first][it.second] } ) //coordinates in min heap
5+
6+
repeat(size) { row -> //add first element of each row
7+
pq.offer(row to 0)
8+
}
9+
10+
var nth = 0
11+
while (true) {
12+
nth++
13+
val poll = pq.poll()
14+
if (nth == kth) return m[poll.first][poll.second]
15+
if (poll.second + 1 < size) { //offer the next element of the row if avails
16+
pq.offer(poll.first to poll.second+1)
17+
}
18+
}
19+
}
20+
}

0 commit comments

Comments
 (0)