HOT 100 › 索引 › B7 链表 Linked List
LC 23合并 K 个升序链表Merge k Sorted Lists 困难
将 k 条升序链表合并为一条升序链表并返回头节点。
思路 小根堆存 k 个当前节点,弹最小接结果、推其后继入堆。时间 O(N log k)。
class Solution: def mergeKLists(self, lists): dummy = cur = ListNode() heap = [(n.val, i, n) for i, n in enumerate(lists) if n] heapq.heapify(heap) while heap: val, i, node = heapq.heappop(heap) cur.next = node cur = cur.next nxt = node.next if nxt: heapq.heappush(heap, (nxt.val, i, nxt)) return dummy.next