Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Problem solving idea One:
Before we had mergetwolists (ListNode L1, ListNode L2) method, the direct call, need k-1 the call, each call needs to produce a listnode[], the space overhead is very large. If the idea of divided treatment, the adjacent two ListNode to mergetwolists, each will reduce the size of half, until the scale becomes 2, the space costs will be much smaller. The Java implementation is as follows:
static public ListNode mergeklists (listnode[] lists) {if (lists.length = = 0) return null;if (lists.length = 1) return lists [0];if (Lists.length = = 2) return mergetwolists (Lists[0], lists[1]);//reference Java for Leetcode 021 Merge, Sorted listselse {L istnode[] halflists = new Listnode[lists.length/2];if (lists.length% 2 = = 0) for (int i = 0; i < halflists.length; i+ +) Halflists[i] = mergetwolists (lists[2 * i], lists[2 * i + 1]); else {for (int i = 0; i < halflists.length; i++) halflist S[i] = mergetwolists (lists[2 * i], lists[2 * i + 1]); Halflists[0] = Mergetwolists (Halflists[0],lists[lists.length-1]);} Return mergeklists (halflists);}}
Two ways to solve problems:
With the priority queue, Java is implemented as follows:
Public ListNode mergeklists (listnode[] lists) {queue<listnode> heap = new Priorityqueue<listnode> (new Comparator<listnode> () {public int compare (ListNode L1, ListNode L2) {return l1.val-l2.val;}}); ListNode dummy = new ListNode (0), cur = dummy, tmp;for (ListNode list:lists) if (list = null) Heap.offer (list); while (!he Ap.isempty ()) {tmp = Heap.poll (); cur.next = Tmp;cur = Cur.next;if (Tmp.next! = null) Heap.offer (tmp.next);} return dummy.next;}
Java for Leetcode 023 Merge K Sorted Lists