Given an
Note that it is the
Example 1:
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Example 2:
Input: matrix = [[-5]], k = 1 Output: -5
Constraints:
n == matrix.length n == matrix[i].length 1 <= n <= 300 -109 <= matrix[i][j] <= 109 - All the rows and columns of
matrix are guaranteed to be sorted in non-decreasing order. 1 <= k <= n2
Solution
這題直覺想到 max heap 的方式來解
把所有的數字存到 max heap,這邊要注意的是
存的過程中,如果 max heap 的長度已經大於 k,就開始 remove
可以想成,因為是 max heap,從後面往前數過來,就是一個遞增數列
所以保持長度k,就代表第一個數字,就是要找的 kth smallest element
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun kthSmallest(matrix: Array<IntArray>, k: Int): Int { | |
val pq = PriorityQueue() {a: Int, b: Int -> b - a} // max heap | |
for(r in matrix.indices) { | |
for(c in matrix[0].indices) { | |
pq.add(matrix[r][c]) | |
if(pq.size > k) { | |
pq.remove() | |
} | |
} | |
} | |
return pq.first() | |
} | |
} |
沒有留言:
張貼留言