使用 heapq 对链表结点对象进行排序

heapq 看起来比 PriorityQueue 要快得多,但是用起来也要麻烦一些,尤其是 heapq 是函数式风格,和对象格格不入。

其实可以直接使用 heapq,只要把链表中所有结点的值存进去就行,但如果只想同时维护 top K 个值在里面呢?就需要做一些调整。

直接上代码:

class Solution:
    def __init__(self):
        setattr(ListNode, '__lt__', lambda self, other: self.val < other.val)

    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        res_head = res = ListNode()
        lists_head = [l for l in lists if l]
        heapq.heapify(lists_head)
        while lists_head:
            head = heapq.heappop(lists_head)
            res.next = ListNode(head.val)
            res = res.next
            if head.next:
                heapq.heappush(lists_head, head.next)
        return res_head.next

相当于是手动指定一个 compartor。为什么可以这样修改,可以看看 heapq 的源码。

def heapify(x):
    """Transform list into a heap, in-place, in O(len(x)) time."""
    n = len(x)
    # Transform bottom-up.  The largest index there's any point to looking at
    # is the largest with a child index in-range, so must have 2*i + 1 < n,
    # or i < (n-1)/2.  If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
    # j-1 is the largest, which is n//2 - 1.  If n is odd = 2*j+1, this is
    # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
    for i in reversed(range(n//2)):
        _siftup(x, i)

def _siftup(heap, pos):
    endpos = len(heap)
    startpos = pos
    newitem = heap[pos]
    # Bubble up the smaller child until hitting a leaf.
    childpos = 2*pos + 1    # leftmost child position
    while childpos < endpos:
        # Set childpos to index of smaller child.
        rightpos = childpos + 1
        if rightpos < endpos and not heap[childpos] < heap[rightpos]:
            childpos = rightpos
        # Move the smaller child up.
        heap[pos] = heap[childpos]
        pos = childpos
        childpos = 2*pos + 1
    # The leaf at pos is empty now.  Put newitem there, and bubble it up
    # to its final resting place (by sifting its parents down).
    heap[pos] = newitem
    _siftdown(heap, startpos, pos)

这里随便举个建堆的例子。建堆的时候,调用了 heap[childpos] < heap[rightpos],如果保存的是对象,会触发对象的比较大小的魔术方法,因此只需要重定义一下类似于 __lt__ 这种方法即可。作为脚本语言,python 在修改定义上还是很容易的。

不过,为什么没有提供自定义 comparator 的方法?这才是最奇怪的地方。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值