题目链接: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 = nextclass Solution:def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:if not lists:return Nonelength = len(lists)return self.merge(lists, 0, length-1)def merge(self, lists, p, r):if p == r:return lists[p]q = (p + r) // 2l1 = 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 l2if l2 is None:return l1dummy = ListNode()cur = dummywhile l1 is not None and l2 is not None:if l1.val < l2.val:cur.next = l1l1 = l1.nextcur = cur.nextelse:cur.next = l2l2 = l2.nextcur = cur.nextcur.next = l1 if l1 is not None else l2return dummy.next
