一、题目
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
二、解题
三、代码实现
class Solution {
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
return partition(lists, 0, lists.count - 1)
}
func partition(_ lists: [ListNode?], _ left: Int, _ right: Int) -> ListNode? {
if left == right {
return lists[left]
}
if left < right {
let mid = (left + right) / 2
let l1 = partition(lists, left, mid)
let l2 = partition(lists, mid + 1, right)
return mergeTwoList(l1, l2)
}
return nil
}
func mergeTwoList(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1!.val > l2!.val {
let tempNode = l2
tempNode?.next = mergeTwoList(l1, l2?.next)
return tempNode
} else {
let tempNode = l1
tempNode?.next = mergeTwoList(l1?.next, l2)
return tempNode
}
}
}
Demo地址:github