题目链接:https://leetcode-cn.com/problems/merge-k-sorted-lists/
难度:困难
描述:
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
提示:
数组中的链表数:[0, 10000]
链表中的节点数:[0, 500]
题解
思路:
基本思想是先合并两个链表,在依次合并(不知道为什么超出时间限制,按理说复杂度也不高)或者归并合并。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists:
return None
length = len(lists)
return self.merge(lists, 0, length-1)
def merge(self, lists, p, r):
if p == r:
return lists[p]
q = (p + r) // 2
l1 = self.merge(lists, p, q)
l2 = self.merge(lists, q+1, r)
return self.merge_two_list(l1, l2)
def merge_two_list(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
dummy = ListNode()
cur = dummy
while l1 is not None and l2 is not None:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
cur = cur.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 is not None else l2
return dummy.next