"023-merge K Sorted Lists (combined with k-lined single-linked list)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Merge K sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Main Topic
Combine k rows of single linked lists. Analyze and describe its complexity.
Thinking of solving problems
Use the small top heap to achieve, the first node of the K-linked list into the heap, take the top element of the heap, the node is the smallest, and then let the next node of the node into the heap, and then take the top element of the heap, which is the second small node, has been such a sub-operation, until all the nodes have been processed, so that the completion of the chain See the code and comments for more details. Suppose K lists have N nodes, the time complexity is O (N*log (k)), and the spatial complexity is O (k).
Code Implementation
Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
Algorithm implementation class
Public class solution {Public ListNode mergeklists (listnode[] lists) {//Is empty or has no elements if(Lists = =NULL|| Lists.length <1) {return NULL; }//Only one element if(Lists.length = =1) {returnlists[0]; }//Create a small top heap and use an anonymous inner class as the comparerMinheap<listnode> minheap =NewMinheap<listnode> (NewComparator<listnode> () {@Overridepublic int Compare (ListNode O1, ListNode O2) {if(O1 = =NULL) {return-1; }if(O2 = =NULL) {return 1; }returnO1.Val-O2.Val; } });//Put the first node of the linked list in the array into a heap for(ListNode node:lists) {if(Node! =NULL) {Minheap.add (node); } }//Head node, for auxiliary useListNode head =NewListNode (0);//node currently being processedListNode Curr = head; while(!minheap.isempty ()) {ListNode node = minheap.deletetop ();//The next node in the node is not empty, and the next node is put into the heap . if(Node.next! =NULL) {Minheap.add (node.next); } curr.next = node; Curr = node; }returnHead.next; }/** * Small Top heap * * @param <T> * * PrivateStatic class minheap<T> { //collection of elements stored in the heap Privatelist<t> items;PrivateComparator<t> comp;/** * Constructs a vertebra, the initial size is the * *Public Minheap (comparator<t> comp) { This( +, comp); }/** * attainments A heap that specifies the initial size * * @param Size Initial sizes */public minheap (int size, comparator<t> comp) {items =Newarraylist<> (size); This. comp = comp; }/** * Adjust the heap upward * * @param Index is the starting position of the moved element */public void Siftup (int index) {T intent = items.get (index);//Gets the element object to start adjusting while(Index >0) {//If not the root elementint parentindex = (Index-1) /2;//Find the location of the parent element objectT parent = Items.get (Parentindex);//Get parent Element Object if(Comp.compare (Intent, parent) <0) {//Move Up condition, child node is smaller than parent nodeItems.set (index, parent);//Delegating the parent nodeindex = Parentindex;//Record the location where the parent node is delegated}Else{The //child nodes are not smaller than the parent node, which indicates that the parent-child path has been sorted from small to large and does not need to be adjusted Break; } }//Index This record is the location of the last delegated parent (and possibly itself) . ///So put the element value of the first adjustment in the index positionItems.set (index, intent); }/** * Adjust the heap down * * @param The starting position of the element where index is moved down */public void Siftdown (int index) {T intent = items.get (index);//Gets the element object to start adjustingint leftindex =2* Index +1;//// Gets the element position of the left Dial hand node of the element object that is starting to adjust while(Leftindex < Items.size ()) {//If there are left dial hand nodesT minchild = Items.get (Leftindex);//takes the element object of the left Dial hand node and assumes that it is the smallest of the two sub-nodesint minindex = Leftindex;The position of the smallest node element in the//two child nodes, assuming the position of the left Dial hand node at the beginningint rightindex = Leftindex +1;//Get the location of the right child node if(Rightindex < Items.size ()) {//If there is a right child nodeT rightchild = Items.get (Rightindex);//Gets the element object of the right child node if(Comp.compare (Rightchild, Minchild) <0) {//Find the child node in two sub-nodesMinchild = Rightchild; Minindex = Rightindex; } }//If the Kid node is smaller than the parent node, it needs to be adjusted downwards if(Comp.compare (Minchild, intent) <0) {Items.set (index, minchild);//Move child nodes upindex = Minindex;//Record the position of the top move nodeLeftindex = Index *2+1;//Find the position of the left child node of the top move node}Else{//The child node is not smaller than the parent node, which indicates that the parent-son path has been sorted from small to large, and does not need to be adjusted Break; } }//Index This record is the position (and possibly itself) of the last child node that was moved up. ///So put the element value of the first adjustment in the index positionItems.set (index, intent); }/** * Add an element to the heap * * @param Item waits for the element to be added */public void Add (T item) {Items.Add (item);//Add elements to the lastSiftup (Items.size ()-1);//Cycle up to complete refactoring}/** * Remove the top element of the heap * * @return The element at the top of the heap */Public T Deletetop () {if(Items.isempty ()) {//If the heap is already empty, report an exception Throw NewRuntimeException ("The heap is empty."); } T MaxItem = Items.get (0);//Get heap top elementT LastItem = Items.remove (Items.size ()-1);//Delete last element if(Items.isempty ()) {after deleting an element, if the heap is empty, it means that the deleted element is also the top element of the heap returnLastItem; } items.set (0, LastItem);//Put the deleted element in the top of the heapSiftdown (0);//Adjust heap from top to bottom returnMaxItem;//Return to top of heap element}/** * Determine if the heap is empty * * @return true is empty, false no */public Boolean isEmpty () {returnItems.isempty (); } }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47016131"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "023-merge K Sorted Lists (merging K-ranked single-linked list)"