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
思路分析:
题目的意思是合并k个有序的链表。
这题可以运用分治法,进行两两合并,转化成第21题(Merge Two Sorted Lists)去解决,直到最后只剩下一个链表。
Java代码:
public class MergekSortedLists {
public static void main(String[] args) {
/**
* Given an array of linked-lists lists, each linked list is sorted in ascending
* order.
*
* Merge all the linked-lists into one sort linked-list and return it.
*
*
*
* Example 1:
*
* Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation:
* The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted
* list: 1->1->2->3->4->4->5->6 Example 2:
*
* Input: lists = [] Output: [] Example 3:
*
* Input: lists = [[]] Output: []
*
*
* Constraints:
*
* k == lists.length 0 <= k <= 10^4 0 <= lists[i].length <= 500 -10^4 <=
* lists[i][j] <= 10^4 lists[i] is sorted in ascending order. The sum of
* lists[i].length won't exceed 10^4.
*/
ListNode list01 = new ListNode(1);
ListNode list04 = new ListNode(4);
ListNode list05 = new ListNode(5);
list01.next = list04;
list04.next = list05;
ListNode list11 = new ListNode(1);
ListNode list13 = new ListNode(3);
ListNode list14 = new ListNode(4);
list11.next = list13;
list13.next = list14;
ListNode list22 = new ListNode(2);
ListNode list26 = new ListNode(6);
list22.next = list26;
ListNode[] lists = new ListNode[] { list01, list11, list22 };
LeetCodeUtil.printNodeList(mergeKLists(lists));
}
public static ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
int interval = 1, length = lists.length;
while (interval < length) {
for (int i = 0; i + interval < length; i += interval * 2) {
lists[i] = mergeTwoList(lists[i], lists[i + interval]);
}
interval *= 2;
}
return lists[0];
}
public static ListNode mergeTwoList(ListNode ln1, ListNode ln2) {
if (ln1 == null) {
return ln2;
}
if (ln2 == null) {
return ln1;
}
ListNode fakeHead = new ListNode(0);
ListNode ln3 = fakeHead;
while (ln1 != null && ln2 != null) {
if (ln1.val < ln2.val) {
ln3.next = ln1;
ln1 = ln1.next;
} else {
ln3.next = ln2;
ln2 = ln2.next;
}
ln3 = ln3.next;
}
if (ln1 != null) {
ln3.next = ln1;
}
if (ln2 != null) {
ln3.next = ln2;
}
return fakeHead.next;
}
}