题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
解题思路一
虽然难度是hard,但是这题用暴力解法效率也还不错。
1、将所有链表的元素放到一个列表中
2、列表中的元素进行排序
3、用排好序的元素生成新的链表。
直接上代码吧,没有需要特别说明的地方。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
temp = []
head = ListNode(0)
q = head
for l in lists:
while l:
temp.append(l.val)
l = l.next
temp.sort()
for each in temp:
q.next = ListNode(each)
q = q.next
return head.next
解题思路二
利用模块 heapq 进行排序,然后构造链表。可以学习一下这个队列,感觉是一个trick。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
head = ListNode(0)
temp = head
heap = []
for l in lists:
while l:
heapq.heappush(heap,l.val)
l = l.next
while heap:
val = heapq.heappop(heap)#按照升序pop数据。
temp.next = ListNode(val)
temp = temp.next
#temp.next = None
return head.next
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists