您的位置:首页 > 其它

Leetcode: Merge k Sorted Lists

2014-11-17 16:24 162 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.

Divide and conquer: Divide the list into two parts, and use recursion to divide the two parts and merge. Time complexity
O(nklogk), n is the length of the longest linked list. Space complexity is the heap size O(logk) 

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.size() == 0) {
return null;
}

if (lists.size() == 1) {
return lists.get(0);
}

ListNode p1 = mergeKLists(lists.subList(0, lists.size() / 2));
ListNode p2 = mergeKLists(lists.subList(lists.size() / 2, lists.size()));
return merge2Lists(p1, p2);
}

private ListNode merge2Lists(ListNode p1, ListNode p2) {
if (p1 == null) return p2;
ListNode dummy = new ListNode(0);
dummy.next = p1;

ListNode h1 = dummy;
ListNode h2 = h1.next;
while (p2 != null) {
if (h2 == null) {
h1.next = p2;
break;
}
if (p2.val < h2.val) {
ListNode temp = p2.next;
h1.next = p2;
p2.next = h2;
p2 = temp;
}
h1 = h1.next;
h2 = h1.next;
}

return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode