您的位置:首页 > 其它

Merge k Sorted Lists--lintcode

2017-08-25 22:37 176 查看
Description

Merge k sorted linked lists and return it as one sorted list.Analyze and describe its complexity.

Example

Given lists:

[

2->4->null,

null,

-1->null

],

return -1->2->4->null.

看到这个题目,脑子里 想到的是 for循环 遍历比较。没有想到基础排序–归并排序。这个题目考的好像就是归并排序。先亮for循环代码。

public ListNode mergeKLists(List<ListNode> lists) {
if(lists==null||lists.size()==0) {
return null;
}
ListNode head = lists.get(0);
for(int i=1;i<lists.size();i++) {
head = mergeTwoLists(head, lists.get(i));
}
return head;
}
ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head    = new ListNode(-1);
ListNode current = head;
while(list1!=null&&list2!=null) {
if(list1.val<list2.val) {
current.next = list1;
list1   = list1.next;
} else {
current.next = list2;
list2   = list2.next;
}
current = current.next;
}
if(list1!=null) {
current.next = list1;
} else {
current.next = list2;
}
return head.next;
}


这个我是盗别人的代码。我写的真的惨不忍睹。正好可以学习学习别人的代码为什么这么简洁。

利用归并排序的代码:

public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists==null || lists.size()==0)
return null;
return helper(lists,0,lists.size()-1);
}
private ListNode helper(ArrayList<ListNode> lists, int l, int r)
{
if(l<r)
{
int m = (l+r)/2;
return merge(helper(lists,l,m),helper(lists,m+1,r));
}
return lists.get(l);
}
private ListNode merge(ListNode l1, ListNode l2)
{
ListNode dummy = new ListNode(0);
dummy.next = l1;
ListNode cur = dummy;
while(l1!=null && l2!=null)
{
if(l1.val<l2.val)
{
l1 = l1.next;
}
else
{
ListNode next = l2.next;
cur.next = l2;
l2.next = l1;
l2 = next;
}
cur = cur.next;
}
if(l2!=null)
cur.next = l2;
return dummy.next;
}


这个也是盗别人的代码。网址:http://blog.csdn.net/linhuanmars/article/details/19899259

这篇博客有两种写法。讲的也挺仔细的。佩服他,太强悍了,向着他前进
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  分治算法 算法