Topic:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Ideas:
1) directly using the merge sorted lists code, but timed out. The reason is that the complexity of this time is too large, 2n + 3n + 4n +. + kn = O (nk^2)
Packagelist; Public classmergeksortedlists { PublicListNode mergeklists (listnode[] lists) {intLen; if(Lists = =NULL|| (len = lists.length) = = 0)return NULL; ListNode Q= Lists[0]; for(inti = 1; i < Len; ++i) {q=mergetwolists (q, lists[i]); } returnQ; } PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode P=NewListNode (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; returnHead.next; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub }}
2) using the idea of merge sort, 22 merges. The complexity of the time is 2N*K/2 + 4N*K/4 +. + (2^x) n*k/(2^x) = Xkn, where x is Logk
Packagelist; Public classmergeksortedlists { PublicListNode mergeklists (listnode[] lists) {intLen; if(Lists = =NULL|| (len = lists.length) = = 0)return NULL; intCur = 0; intEnd = Len-1; while(End > 0) {cur= 0; while(Cur <end) {Lists[cur]=mergetwolists (Lists[cur], lists[end]); ++cur; --end; } } returnLists[0]; } PublicListNode mergetwolists (listnode L1, ListNode L2) {ListNode P=NewListNode (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; returnHead.next; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub }}
Leetcode-merge k Sorted Lists