Leetcode--merge k Sorted Lists

Source: Internet
Author: User

Discription:

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

Subscribe to see which companies asked this question.

Idea: In fact, the merge sort is the last step of the merge operation. Thought is recursive division, first a big problem is divided into 2 sub-problems, and then the solution of 2 sub-problems to merge. An orderly sequence can be found after a single traversal. Even if the conditions given in the topic, there is already a list of K has been sequenced. Then recursively divide the problem into 2, 4 .... Logk a sequence of substrings. The solution for each of the two subsequence is then merged. Finally get a list of well-ordered lists. The time complexity is O (NLOGK).

Code:

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { PublicListNode merge2lists (ListNode list1, ListNode list2) {ListNode head=NewListNode (0); ListNode cur=Head;  while(List1! =NULL&& List2! =NULL) {            if(List1.val <list2.val) {Cur.next=List1; List1=List1.next; }            Else{Cur.next=List2; List2=List2.next; } cur=Cur.next; }                 while(List1! =NULL) {Cur.next=List1; List1=List1.next; Cur=Cur.next; }                 while(List2! =NULL) {Cur.next=List2; List2=List2.next; Cur=Cur.next; }                returnHead.next; }         PublicListNode mergeklists (listnode[] lists) {if(Lists = =NULL|| Lists.length = = 0) {            return NULL; }                if(Lists.length = = 1) {            returnLists[0]; }                intMID = Lists.length/2; ListNode List1= Mergeklists (arrays.copyofrange (lists, 0, mid)); ListNode List2=mergeklists (Arrays.copyofrange (lists, Mid, lists.length)); returnmerge2lists (List1, List2); }}

Why is the problem of Java so high efficiency, the C + + has been blown out.

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.