Leetcode-merge k Sorted Lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.