给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例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 = []
输出:[]
示例:
输入:lists = [[]]
输出:[]
提示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
public ListNode mergeKLists(ListNode[] lists) {
ListNode h = new ListNode();
ListNode head;
if(lists.length == 0) return null;
for(int i = 0; i < lists.length; i++){
if (lists[i] == null){
ListNode t = new ListNode();
t.val = Integer.MAX_VALUE;
lists[i] = t;
}
}
head=h;
int count= 0,flag=0,min = Integer.MAX_VALUE-1;
for(int i = 0; ;i++){
if (lists[i].val == Integer.MAX_VALUE) {
count++;
}
if(lists[i].val<=min){
flag=i;
min = lists[i].val;
}
if(i==lists.length - 1){
ListNode tem = new ListNode();
if(lists[flag].val!= Integer.MAX_VALUE)
{
tem.val = lists[flag].val;
h.next = tem;
h = h.next;
}
if(lists[flag].next != null)
lists[flag]=lists[flag].next;
else{
lists[flag].val = Integer.MAX_VALUE;
}
if(count==lists.length) break;
min = Integer.MAX_VALUE-1;
i=-1;
count = 0;
}
}
return head.next;
}
虽然执行用时和内存消耗都不小,但是也是自己一点一点撕出来的。也得记录一下