题目描述
题目难度:Hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
- Input:
[
1->4->5,
1->3->4,
2->6
]
- Output:
1->1->2->3->4->4->5->6
AC代码
leetcode 优秀的解法:灵活运用二路归并排序的思想。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
return partition(lists, 0, lists.length - 1);
}
private ListNode partition(ListNode[] lists, int start, int end){
if(start == end) return lists[start];
if(start < end){
int mid = (start + end) >> 1;
ListNode l1 = partition(lists, start, mid);
ListNode l2 = partition(lists, mid + 1, end);
return mergeCore(l1, l2);
}
else return null;
}
//合并两个链表,返回合并后的头结点
private ListNode mergeCore(ListNode l1, ListNode l2){
if(l1 != null && l2 != null){
if(l1.val < l2.val){
l1.next = mergeCore(l1.next, l2);
return l1;
}
else{
l2.next = mergeCore(l1, l2.next);
return l2;
}
}
if(l1 != null) return l1;
else return l2;
}
}