Algorithm icon indicating copy to clipboard operation
Algorithm copied to clipboard

python的heapq使用方式(堆)

Open jinlukang1 opened this issue 4 years ago • 0 comments

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        n = len(matrix)
        pq = [(matrix[i][0], i, 0) for i in range(n)]
        heapq.heapify(pq)

        for i in range(k-1):
            num, x, y = heapq.heappop(pq)
            if y != n - 1:
                heapq.heappush(pq, (matrix[x][y+1], x, y + 1))
        
        return heapq.heappop(pq)[0]


jinlukang1 avatar Aug 12 '20 13:08 jinlukang1