23. 合并K个排序链表
2020-03-11 本文已影响0人
寂灭天骄小童鞋
https://leetcode-cn.com/problems/merge-k-sorted-lists/
func mergeKLists(_ lists: [ListNode?]) -> ListNode? {
var mulLists = lists
if mulLists.count <= 0 {return nil}
var step = 1
while step < mulLists.count {
let nextStep = step << 1
for idx in stride(from: 0, to: mulLists.count - step, by: nextStep) {
mulLists[idx] = mergeTwoLists(mulLists[idx], mulLists[idx + step])
}
step = nextStep
}
return mulLists[0]
}
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil {return l2}
if l2 == nil {return l1}
let dummyNode = ListNode(0)
var cur = dummyNode
var L1 = l1
var L2 = l2
while L1 != nil && L2 != nil {
if L1!.val > L2!.val {
cur.next = L2!
cur = L2!
L2 = L2?.next
} else {
cur.next = L1!
cur = L1!
L1 = L1?.next
}
}
if L1 != nil {
cur.next = L1
}
if L2 != nil {
cur.next = L2
}
return dummyNode.next
}