[Problem]
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
[Analysis]
As soon as this question comes up, you'll think of the merge two Sorted Lists that I've done before. But if you simply keep the new list merge into the result, the complexity is very high, because you can think about it and find that the elements that have been mixed in the results in this process need to be reordered, and this part of the effort is optimized by using reasonable techniques. What you need here is the heap data structure. It's easier to think about the steps after the heap, just put all the list head in the heap, take a link to the top one at a time, and put its next in the heap (if it exists) until the heap is empty and all the elements are accessed once. Both the access element and the complexity of the link are O (1), and the complexity of the heap to the new element is O (log (k)), so the complexity of the entire algorithm is O (log (k) * N), n is the sum of the number of elements in all lists.
* Note that there are many null case needs to be judged.
* The heap implementation in Java is priorityqueue.
[Solution]
ImportJava.util.Comparator;ImportJava.util.PriorityQueue; Public classSolution { PublicListNode mergeklists (listnode[] lists) {intSize =lists.length; if(Size = = 0) { return NULL; } if(Size = = 1) { returnLists[0]; } priorityqueue<ListNode> heap =NewPriorityqueue<listnode>( 2, NewComparator<listnode>() {@Override Public intCompare (ListNode node1, ListNode node2) {returnNode1.val-Node2.val; } } ); for(ListNode node:lists) {if(Node! =NULL) {Heap.add (node); }} ListNode head=NULL; ListNode cur=NULL; while(!Heap.isempty ()) {ListNode node=Heap.poll (); if(Node.next! =NULL) {heap.add (node.next); } if(Head = =NULL) {Head=node; Cur=node; } Else{Cur.next=node; Cur=Cur.next; } } returnHead; } }
Leetcode #23 Merge k Sorted Lists (H)