|
| 1 | +// id: 23 |
| 2 | +// Name: Merge k Sorted Lists |
| 3 | +// link: https://leetcode.com/problems/merge-k-sorted-lists/ |
| 4 | +// Difficulty: Hard |
| 5 | + |
| 6 | +class Solution { |
| 7 | + public ListNode mergeKLists(ListNode[] lists) { |
| 8 | + if (lists == null || lists.length == 0) return null; |
| 9 | + return mergeListsHelper(lists, 0, lists.length - 1); |
| 10 | + } |
| 11 | + |
| 12 | + private ListNode mergeListsHelper(ListNode[] lists, int start, int end) { |
| 13 | + int mid = (start + end) / 2; |
| 14 | + if (start >= end) return lists[start]; |
| 15 | + |
| 16 | + ListNode first = mergeListsHelper(lists, start, mid); |
| 17 | + ListNode second = mergeListsHelper(lists, mid+1, end); |
| 18 | + return merge2Lists(first, second); |
| 19 | + } |
| 20 | + |
| 21 | + private ListNode merge2Lists(ListNode first, ListNode second) { |
| 22 | + // make dummy node for easier addition |
| 23 | + ListNode head = new ListNode(-1); |
| 24 | + ListNode tail = head; |
| 25 | + |
| 26 | + |
| 27 | + while (first != null && second != null) { |
| 28 | + if (first.val < second.val) { |
| 29 | + tail.next = first; |
| 30 | + first = first.next; |
| 31 | + } |
| 32 | + else { |
| 33 | + tail.next = second; |
| 34 | + second = second.next; |
| 35 | + } |
| 36 | + tail = tail.next; |
| 37 | + } |
| 38 | + |
| 39 | + // only 1 of the following if will run |
| 40 | + if (first != null) { |
| 41 | + tail.next = first; |
| 42 | + } |
| 43 | + if (second != null) { |
| 44 | + tail.next = second; |
| 45 | + } |
| 46 | + |
| 47 | + return head.next; |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | + //////////////////////////////////// SECOND APPROACH |
| 54 | + public ListNode mergeKLists__approach2(ListNode[] lists) { |
| 55 | + |
| 56 | + // create a list object for merged lists |
| 57 | + ListNode head = null; |
| 58 | + ListNode tail = null; |
| 59 | + |
| 60 | + while (true) { |
| 61 | + // find the minimum elment from lists |
| 62 | + int minNodeIndex = -1; |
| 63 | + |
| 64 | + // minimum can also be fined using Priority Queue |
| 65 | + // but PrioriryQueue will use extra space |
| 66 | + |
| 67 | + for (int i = 0; i < lists.length; i++) { |
| 68 | + if (lists[i] == null) continue; |
| 69 | + |
| 70 | + if ( |
| 71 | + minNodeIndex == -1 || // not initialized |
| 72 | + lists[i].val < lists[minNodeIndex].val |
| 73 | + ){ |
| 74 | + minNodeIndex = i; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if (minNodeIndex == -1) { |
| 79 | + break; // all lists are merged |
| 80 | + } |
| 81 | + else { |
| 82 | + if ( head == null ) { |
| 83 | + head = tail = lists[minNodeIndex]; |
| 84 | + } |
| 85 | + else { |
| 86 | + tail.next = lists[minNodeIndex]; |
| 87 | + tail = tail.next; |
| 88 | + } |
| 89 | + lists[minNodeIndex] = lists[minNodeIndex].next; |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + return head; |
| 94 | + } |
| 95 | +} |
0 commit comments