How to make heapq evaluate the heap off of a specific attribute?

    技术2022-07-20  72

    python怎么赋予堆元素额外的属性

    问题:python怎么赋予堆元素额外的属性针对问题代码解释

    问题:python怎么赋予堆元素额外的属性

    我想要保留一些对象并将它们作为堆进行处理,它们不仅仅具有整数属性,同时还具有其他属性。如何同时作为推对象保存这些属性并在需要的时候调用它们。

    针对问题

    leetcode 378. 有序矩阵中第K小的元素 给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第 k 小的元素。 请注意,它是排序后的第 k 小元素,而不是第 k 个不同的元素。 示例 matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, 返回 13。

    代码

    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) ret = 0 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] 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/solution/you-xu-ju-zhen-zhong-di-kxiao-de-yuan-su-by-leetco/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    解释

    pq = [(matrix[i][0], i, 0) for i in range(n)] heapq.heapify(pq)

    通过这种方式生成的堆可以通过元组里的第一个元素进行排序,同时还保留了起坐标值,方便后续的调用。 同样的例子还有:

    >>> h = [] >>> heappush(h, (5, 'write code')) >>> heappush(h, (7, 'release product')) >>> heappush(h, (1, 'write spec')) >>> heappush(h, (3, 'create tests')) >>> heappop(h) (1, 'write spec')
    Processed: 0.009, SQL: 10