π‘ Python 3
- Kth Smallest Element in a Sorted Matrix [Link]
μ€ν°λ μ§λμ λ§μΆ°μ νμΌλ‘ νμλλ° λ μ’μ λ°©λ²μ΄ μμ§ μμκΉ μΆλ€.
κ·Έλ κ² ν¨μ¨μ μΈ μ½λλ μλ κ² κ°λ€λ μκ°μ΄ μ€λ©μ€λ© μ¬λΌμ¨λ€.
heapq.nsmallest
λ₯Ό ν λ² μ¨λ³΄κ³ μΆμλλ° μ΄λ²μ μ μ©ν΄λ΄€λ€.
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
heap = []
for mat in matrix:
for ele in mat:
heapq.heappush(heap, ele)
return heapq.nsmallest(k, heap)[-1]