leetcode | 378 Kth Smallest Element in a Sorted Matrix

tjddus0302Β·2022λ…„ 6μ›” 27일
0

Algorithm_python

λͺ©λ‘ 보기
85/85
post-thumbnail

πŸ’‘ Python 3






πŸ”— 문제


  1. 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]






참고 자료


heapq β€” νž™ 큐 μ•Œκ³ λ¦¬μ¦˜

heapqλͺ¨λ“ˆμ— μžˆλŠ” nlargeest(), nsmallest() ν•¨μˆ˜

0개의 λŒ“κΈ€