美文网首页
23. 合并K个排序链表

23. 合并K个排序链表

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-11 17:15 被阅读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
    }
    
    

    相关文章

      网友评论

          本文标题:23. 合并K个排序链表

          本文链接:https://www.haomeiwen.com/subject/sabgdhtx.html