-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23.合并-k-个升序链表.go
84 lines (79 loc) · 1.41 KB
/
23.合并-k-个升序链表.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* @lc app=leetcode.cn id=23 lang=golang
*
* [23] 合并 K 个升序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeKLists(lists []*ListNode) *ListNode {
/* 分治 + 合并链表 */
if len(lists) == 0 {
return nil
}
if len(lists) == 1 {
return lists[0]
}
start := 0
end := len(lists) - 1
// 合并两个有序链表
var mergeTwo func(*ListNode, *ListNode) *ListNode
mergeTwo = func(a, b *ListNode) *ListNode {
if a == nil {
return b
}
if b == nil {
return a
}
/*
不能使用递归, 否则报内存溢出
if a.Val < b.Val {
a.Next = mergeTwo(a.Next, b)
return a
} else {
b.Next = mergeTwo(b.Next, b)
return b
}
*/
head := &ListNode{
Val: 0,
}
tail := head
for a != nil && b != nil {
if a.Val < b.Val {
tail.Next = a
a = a.Next
} else {
tail.Next = b
b = b.Next
}
tail = tail.Next
}
if a == nil {
tail.Next = b
}
if b == nil {
tail.Next = a
}
return head.Next
}
// 分治, 二等拆分
var split func(start, end int) *ListNode
split = func(start, end int) *ListNode {
// 拆到只剩一个元素
if start == end {
return lists[start]
}
mid := start + (end-start)/2
left := split(start, mid)
right := split(mid+1, end)
return mergeTwo(left, right)
}
return split(start, end)
}
// @lc code=end