Description

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6


Ideas

這題指示merge 2 lists的延伸。

要過LeetCode的online judge的話必須使用分治法來將list的array分組再兩兩merge。


Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
func mergeKLists(lists []*ListNode) *ListNode {
    if lists == nil || len(lists) == 0 {
        return nil
    }
    return helper(lists, 0, len(lists) - 1)
}

func helper(lists []*ListNode, low int, high int) *ListNode {
    if (low < high) {
        mid := (low + high) / 2
        left := helper(lists, low, mid)
        right := helper(lists, mid+1, high)
        return mergeTwo(left, right)
    }
    return lists[low]
}

func mergeTwo(list1 *ListNode, list2 *ListNode) *ListNode {
    if list1 == nil {
        return list2
    }
    if list2 == nil {
        return list1
    }
    head := &ListNode{}
    p := head
    for list1 != nil && list2 != nil {
        if list1.Val < list2.Val {
            p.Next = list1
            p = p.Next
            list1 = list1.Next
        } else {
            p.Next = list2
            p = p.Next
            list2 = list2.Next
        }
    }
    if list1 != nil {
        p.Next = list1;
    }
    if list2 != nil {
        p.Next = list2;
    }
    return head.Next
}