[LeetCode] 23. Merge k Sorted Lists(合并 k 个有序链表)
- Difficulty: Hard
- Related Topics: Linked List, Divide and Conquer, Heap
- Link: https://leetcode.com/problems/merge-k-sorted-lists/
Description
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
给定包含 k
个单链表的数组 lists
,每个链表都已升序排序。
Merge all the linked-lists into one sorted linked-list and return it.
合并所有链表为一个链表并返回之。
Examples
Example 1
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2
Input: lists = []
Output: []
Example 3
Input: lists = [[]]
Output: []
Constraints
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i]
is sorted in ascending order.- The sum of
lists[i].length
won't exceed10^4
.
Solution
这题的解题思路与归并排序十分相似,我们只要先把 lists
的左半部份合并,再将其右半部份合并,最后将两个合并的结果合并即可,代码如下:
class Solution {
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
if (lists.isEmpty()) {
return null
}
if (lists.size == 1) {
return lists[0]
}
val mid = lists.size / 2
val leftResult = mergeKLists(lists.sliceArray(0 until mid))
val rightResult = mergeKLists(lists.sliceArray(mid until lists.size))
return mergeResult(leftResult, rightResult)
}
private fun mergeResult(left: ListNode?, right: ListNode?): ListNode? {
val dummy = ListNode(-1)
var p = left
var q = right
var r: ListNode? = dummy
while (p != null && q != null) {
if (p.`val` < q.`val`) {
r?.next = p
p = p.next
} else {
r?.next = q
q = q.next
}
r = r?.next
}
if (p != null) {
r?.next = p
}
if (q != null) {
r?.next = q
}
return dummy.next
}
}