题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
1 2 3 4 5 6 7 8 9 10
| 输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
|
示例 2:
示例 3:
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
思路
分治的思想,我们每次两个两个合并,然后在两个两个合并
实现
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
| private static class Solution { public ListNode mergeKLists(ListNode[] lists) { return merge(lists, 0, lists.length - 1); }
private ListNode merge(ListNode[] lists, int left, int right) { if (left == right) { return lists[left]; } if (left > right) { return null; } int mid = (left + right) / 2; return mergeTwolist(merge(lists, left, mid), merge(lists, mid + 1, right)); }
private ListNode mergeTwolist(ListNode node1, ListNode node2) { ListNode preHead = new ListNode(-1); ListNode head = preHead;
while (node1 != null && node2 != null) { if (node1.val <= node2.val) { head.next = node1; node1 = node1.next; } else { head.next = node2; node2 = node2.next; } head = head.next; } head.next = node1 == null ? node2 : node1;
return preHead.next; } }
|