[LeetCode]23 合并K个排序链表

题目描述

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
h = []
head = ListNode(-1)
tmp = head
for i in range(len(lists)):
if lists[i] != None:
heapq.heappush(h, (lists[i].val, i))
while len(h) != 0:
_, loc = heapq.heappop(h)
tmp.next = lists[loc]
tmp = tmp.next
lists[loc] = lists[loc].next
if lists[loc] != None:
heapq.heappush(h, (lists[loc].val, loc))
return head.next