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