23. Merge k Sorted Lists
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个有序链表,采用分治的思想,时间复杂度O(nlogk)
代码:
代码语言:javascript复制/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
return helper(lists, 0, lists.length - 1);
}
private ListNode helper(ListNode[] lists, int start, int end) {
if (start == end) return lists[start];
int mid = (end - start) / 2 start;
ListNode first = helper(lists, start, mid);
ListNode second = helper(lists, mid 1, end);
ListNode head = new ListNode(-1);
ListNode cur = head;
while (first != null && second != null) {
if (first.val < second.val) {
cur.next = first;
first = first.next;
} else {
cur.next = second;
second = second.next;
}
cur = cur.next;
}
if (first == null)
cur.next = second;
if (second == null)
cur.next = first;
return head.next;
}
}