Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
Solution 1:
Time: O(Nlgk)
Space: O(N)
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } ListNode dummy = new ListNode(-1); ListNode cur = dummy; PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val); // need to check list null as well for(ListNode list: lists) { if (list != null) { pq.add(list); } } while(!pq.isEmpty()) { ListNode node = pq.poll(); cur.next = node; cur = cur.next; if (node.next != null) { pq.add(node.next); } } return dummy.next; } }
solution 2:
Time: O(Nlgk)
Space: O(N)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } ListNode res = sort(lists, 0, lists.length - 1); return res; } private ListNode sort(ListNode[] lists, int low, int high) { if (low >= high) { return lists[high]; } int mid = low + (high - low) / 2; ListNode left = sort(lists, low, mid); ListNode right = sort(lists, mid + 1, high); return merge(left, right); } private ListNode merge(ListNode aNode, ListNode bNode) { if (aNode == null) { return bNode; } if (bNode == null) { return aNode; } if (aNode.val <= bNode.val) { aNode.next = merge(aNode.next, bNode); return aNode; } else { bNode.next = merge(aNode, bNode.next); return bNode; } } }