题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入: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:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
提示:
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4lists[i]按 升序 排列lists[i].length的总和不超过10^4
解法一
思路:
额外创建一个结果链表,从待选节点中选择出值最小的节点加入结果链表,同时更新待选节点。
代码:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode mergeKLists(ListNode[] lists) {if (lists == null || lists.length == 0) return null;ListNode dummy = new ListNode(0);ListNode cur = dummy;int stopFlag=0;for (ListNode list : lists) {if(list != null) stopFlag++;}if (stopFlag == 0) return null;int minIndex=0;while (stopFlag > 0) {minIndex=findMin(lists);int val=lists[minIndex].val;ListNode tmp=new ListNode(val);cur.next = tmp;cur=cur.next;lists[minIndex]=lists[minIndex].next;if(lists[minIndex]==null) stopFlag--;}return dummy.next;}public int findMin(ListNode[] head) {int minIndex = -1;for (int i = 0; i < head.length; i++) {if (head[i] != null) {if (minIndex == -1 || head[i].val < head[minIndex].val) {minIndex = i;}}}return minIndex;}
}
解法二
思路:
来自官方的解答。
用分治的方法进行合并。


代码:
class Solution {public ListNode mergeKLists(ListNode[] lists) {return merge(lists, 0, lists.length - 1);}public ListNode merge(ListNode[] lists, int l, int r) {if (l == r) {return lists[l];}if (l > r) {return null;}int mid = (l + r) >> 1;return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));}public ListNode mergeTwoLists(ListNode a, ListNode b) {if (a == null || b == null) {return a != null ? a : b;}ListNode head = new ListNode(0);ListNode tail = head, aPtr = a, bPtr = b;while (aPtr != null && bPtr != null) {if (aPtr.val < bPtr.val) {tail.next = aPtr;aPtr = aPtr.next;} else {tail.next = bPtr;bPtr = bPtr.next;}tail = tail.next;}tail.next = (aPtr != null ? aPtr : bPtr);return head.next;}
}
解法三
思路:
- 每个链表的第一个节点作为候选加入一个小顶堆(
PriorityQueue)。 - 每次从堆里取出值最小的节点,接到结果链表末尾。
- 如果取出的节点还有下一个节点,则把它的下一个节点加入堆。
- 重复,直到堆为空
代码:
class Solution {class Status implements Comparable<Status> {int val;ListNode ptr;Status(int val, ListNode ptr) {this.val = val;this.ptr = ptr;}public int compareTo(Status status2) {return this.val - status2.val;}}PriorityQueue<Status> queue = new PriorityQueue<Status>();public ListNode mergeKLists(ListNode[] lists) {for (ListNode node: lists) {if (node != null) {queue.offer(new Status(node.val, node));}}ListNode head = new ListNode(0);ListNode tail = head;while (!queue.isEmpty()) {Status f = queue.poll();tail.next = f.ptr;tail = tail.next;if (f.ptr.next != null) {queue.offer(new Status(f.ptr.next.val, f.ptr.next));}}return head.next;}
}