author: Blankj blog : http://blankj.com time : 2017/10/15 desc :
| 14 | * </pre> |
| 15 | */ |
| 16 | public class Solution { |
| 17 | // public ListNode mergeKLists(ListNode[] lists) { |
| 18 | // if (lists.length == 0) return null; |
| 19 | // return helper(lists, 0, lists.length - 1); |
| 20 | // } |
| 21 | // |
| 22 | // private ListNode helper(ListNode[] lists, int left, int right) { |
| 23 | // if (left >= right) return lists[left]; |
| 24 | // int mid = left + right >>> 1; |
| 25 | // ListNode l0 = helper(lists, left, mid); |
| 26 | // ListNode l1 = helper(lists, mid + 1, right); |
| 27 | // return merge2Lists(l0, l1); |
| 28 | // } |
| 29 | // |
| 30 | // private ListNode merge2Lists(ListNode l0, ListNode l1) { |
| 31 | // ListNode node = new ListNode(0), tmp = node; |
| 32 | // while (l0 != null && l1 != null) { |
| 33 | // if (l0.val <= l1.val) { |
| 34 | // tmp.next = new ListNode(l0.val); |
| 35 | // l0 = l0.next; |
| 36 | // } else { |
| 37 | // tmp.next = new ListNode(l1.val); |
| 38 | // l1 = l1.next; |
| 39 | // } |
| 40 | // tmp = tmp.next; |
| 41 | // } |
| 42 | // tmp.next = l0 != null ? l0 : l1; |
| 43 | // return node.next; |
| 44 | // } |
| 45 | |
| 46 | public ListNode mergeKLists(ListNode[] lists) { |
| 47 | if (lists.length == 0) return null; |
| 48 | PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() { |
| 49 | @Override |
| 50 | public int compare(ListNode o1, ListNode o2) { |
| 51 | if (o1.val < o2.val) return -1; |
| 52 | else if (o1.val == o2.val) return 0; |
| 53 | else return 1; |
| 54 | } |
| 55 | }); |
| 56 | ListNode node = new ListNode(0), tmp = node; |
| 57 | for (ListNode l : lists) { |
| 58 | if (l != null) queue.add(l); |
| 59 | } |
| 60 | while (!queue.isEmpty()) { |
| 61 | tmp.next = queue.poll(); |
| 62 | tmp = tmp.next; |
| 63 | if (tmp.next != null) queue.add(tmp.next); |
| 64 | } |
| 65 | return node.next; |
| 66 | } |
| 67 | |
| 68 | public static void main(String[] args) { |
| 69 | Solution solution = new Solution(); |
| 70 | ListNode.print(solution.mergeKLists(new ListNode[]{ |
| 71 | ListNode.createTestData("[1,3,5,7]"), |
| 72 | ListNode.createTestData("[2,4,6]") |
| 73 | })); |
nothing calls this directly
no outgoing calls
no test coverage detected