题目描述:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
输入:
1->4->5,
1->3->4,
2->6
输出:
1->1->2->3->4->4->5->6
题意:
题目描述
题解:
按照排序两个链表,找一个基准直接搞
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if(len == 0 || lists == null) return null;
ListNode head = null;
for(int i = 0; i < len; i ++){
head = merge(head,lists[i]);
}
return head;
}
public ListNode merge(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode head = new ListNode(-1);
ListNode count = head;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
count.next = l2;
l2 = l2.next;
}
else{
count.next = l1;
l1 = l1.next;
}
count = count.next;
}
count.next = l1 == null ? l2 : l1;
return head.next;
}
}