描述
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
样例
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null.
代码实现
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
if (lists.size() == 0 || lists == null) {
return null;
}
return mergeHelper(lists, 0, lists.size()-1);
}
// divde and conquer
private ListNode mergeHelper(List<ListNode> lists, int start, int end) {
if (start == end) {
return lists.get(start);
}
int mid = start + (end - start) / 2;
ListNode left = mergeHelper(lists, start, mid);
ListNode right = mergeHelper(lists, mid+1, end);
return mergeTwoLists(left, right);
}
//merge two sorted lists
private ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (list1 != null && list2 != null) {
if (list1.val > list2.val) {
tail.next = list2;
tail = tail.next;
list2 = list2.next;
} else {
tail.next = list1;
tail = tail.next;
list1 = list1.next;
}
}
if (list1 != null) {
tail.next = list1;
} else {
tail.next = list2;
}
return dummy.next;
}
}