LeetCode


题目:

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

思路:

1)直接利用Merge two sorted lists的代码,但超时了。原因是这个时间复杂度太大,2n + 3n + 4n +..+ kn = O(nk^2)

package list;

public class MergeKSortedLists {

public ListNode mergeKLists(ListNode[] lists) {
int len;
if (lists == null || (len = lists.length) == 0) return null;
ListNode q
= lists[0];
for (int i = 1; i < len; ++i) {
q
= mergeTwoLists(q, lists[i]);
}

return q;
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p
= new ListNode(0);
p.next
= null;
ListNode head
= p;

while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next
= l1;
l1
= l1.next;
}
else {
p.next
= l2;
l2
= l2.next;
}
p
= p.next;
}

p.next
= l1 == null ? l2 : l1;
return head.next;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

2)运用merge sort的思想,两两合并。时间复杂度是2n*k/2 + 4n*k/4 + .. + (2^x)n*k/(2^x) = xkn,其中x为logk

package list;

public class MergeKSortedLists {

public ListNode mergeKLists(ListNode[] lists) {
int len;
if (lists == null || (len = lists.length) == 0) return null;

int cur = 0;
int end = len - 1;
while (end > 0) {
cur
= 0;
while (cur < end) {
lists[cur]
= mergeTwoLists(lists[cur], lists[end]);
++cur;
--end;
}
}

return lists[0];
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p
= new ListNode(0);
p.next
= null;
ListNode head
= p;

while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next
= l1;
l1
= l1.next;
}
else {
p.next
= l2;
l2
= l2.next;
}
p
= p.next;
}

p.next
= l1 == null ? l2 : l1;
return head.next;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5060690.html     作者:Merge k Sorted Lists - NULL00     发布日期:2015/12/20     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号