[Leedcode 23] Merge k Sorted Lists

Source: Internet
Author: User

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution {//There are two kinds of solutions, one is to compare all the linked list, because each node needs to compare K times, total kn nodes so the time complexity is O (KNK)//the second one draws on the two-point sequencing method, T (k) =2t (K/2) +o (NK), and the time complexity is O (NKLOGK)     PublicListNode mergeklists (listnode[] lists) {if(lists.length<1)return NULL; if(lists.length==1)returnLists[0]; returnMerge1 (lists,0,lists.length-1); }     PublicListNode merge1 (listnode[] lists,intStartintend) {               if(start<end) {            intMid= (start+end)/2; ListNode L1=Merge1 (Lists,start,mid); ListNode L2=merge1 (lists,mid+1, end); returnMerge2 (L1,L2);//Two-point sorting}Else{            returnLists[start]; }    }         PublicListNode merge2 (listnode l1,listnode L2) {ListNode Newhead=NewListNode (-1); ListNode Temp=Newhead;  while(l1!=NULL&&l2!=NULL){            if(l1.val<l2.val) {Temp.next=L1; L1=L1.next; }Else{Temp.next=L2; L2=L2.next; } temp=Temp.next; }        if(l1!=NULL) {Temp.next=L1; }        if(l2!=NULL) {Temp.next=L2; }        returnNewhead.next; }}

[Leedcode 23] 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.