Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Branching strategy: Each time you merge a list of two ordered lists until you have only one list left.
public class Solution {public ListNode mergeklists (list<listnode> lists) {//Handling Special cases if (lists = = null) return null; int length = Lists.size (); if (length = = 0) return null; if (length = = 1) return lists.get (0); listnode Low, high; while (length! = 1) {//merge the ordered string int index one by one; for (index = 0, index < LENGTH/2; ++index) {low = Lists.get (2*index); High = Lists.get (2*index+1); Lists.set (Index, merge2lists (Low, high)); } if (length%2 = = 1) lists.set (index, Lists.get (length-1)); Length = (length + 1)/2; } return Lists.get (0); ListNode merge2lists (ListNode Low, ListNode high) {ListNode result = new ListNode (-1); ListNode p = result; while (low! = NULL && high ! = null) {if (Low.val < high.val) {p.next = low; low = Low.next; p = p.next; } else {p.next = high; High = High.next; p = p.next; }} if (low = = null) P.next = high; else P.next = low; return result.next; }}
Priority queue (or heap sort): http://zh.wikipedia.org/zh/%E5%84%AA%E5%85%88%E4%BD%87%E5%88%97
public class Solution {//This segment of code is from Https://oj.leetcode.com/discuss/25518/13-lines-in-java public ListNode Mergeklists (list<listnode> lists) { queue<listnode> heap = new Priorityqueue (New comparator< Listnode> () { @Override public int compare (ListNode L1, ListNode L2) { return l1.val-l2.val; } }); ListNode head = new ListNode (0), tail = head; for (ListNode node:lists) if (node! = null) heap.offer (node); while (!heap.isempty ()) { Tail.next = Heap.poll (); tail = Tail.next; if (tail.next! = null) Heap.offer (tail.next); } return head.next;} }
Leetcode--Merge k Sorted Lists (Divide and Conquer/priorityqueue)