Leetcode 23 合并k个升序链表 (每日一题 20210722)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 23 合并k个升序链表 (每日一题 20210722)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給你一個鏈表數(shù)組,每個鏈表都已經(jīng)按升序排列。請你將所有鏈表合并到一個升序鏈表中,返回合并后的鏈表。示例 1:輸入:lists = [[1,4,5],[1,3,4],[2,6]]
輸出:[1,1,2,3,4,4,5,6]
解釋:鏈表數(shù)組如下:
[1->4->5,1->3->4,2->6
]
將它們合并到一個有序鏈表中得到。
1->1->2->3->4->4->5->6
示例 2:輸入:lists = []
輸出:[]
示例 3:輸入:lists = [[]]
輸出:[]鏈接:https://leetcode-cn.com/problems/merge-k-sorted-listsclass Solution:def mergeKLists(self, lists: List[ListNode]) -> ListNode:n = len(lists)if n == 0:return Noneif n == 1:return lists[0]mid = n // 2return self.mergeTwoList(self.mergeKLists(List[:mid]), self.mergeKLists(List[mid:]))def mergeTwoList(self, node1, node2):dummpy = cur = ListNode()while node1 and node2:if node1.val < node2.val:cur.next = node1node1 = node1.nextelse:cur.next = node2node2 = node2.nextcur = cur.nextcur.next = node1 if node1 else node2return dummpy.next
總結(jié)
以上是生活随笔為你收集整理的Leetcode 23 合并k个升序链表 (每日一题 20210722)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 64 最小路径和 (每
- 下一篇: Leetcode 61 旋转链表 (每日