给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 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
不知道为什么,LeetCode总是喜欢把链表题的难度定的虚高...... 这题是困难就挺离谱。
上代码:
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null) {
return null;
}
ListNode node = new ListNode();
ListNode result = node;
while (!emptyAll(lists)) {
int minIndex = 0;
ListNode minNode = null;
for (int index = 0; index < lists.length; index ++) {
ListNode temp = lists[index];
if (temp == null) continue;
if (minNode == null) {
minNode = temp;
minIndex = index;
continue;
}
if (temp.val < minNode.val) {
minNode = temp;
minIndex = index;
}
}
node.next = minNode;
node = node.next;
lists[minIndex] = lists[minIndex].next;
}
return result.next;
}
private static boolean emptyAll(ListNode[] listNodes) {
for (ListNode node : listNodes) {
if (node != null) {
return false;
}
}
return true;
}