image.png

解决思路

优先级队列

  1. public ListNode mergeKLists(ListNode[] lists) {
  2. if (lists == null || lists.length == 0) return null;
  3. PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
  4. @Override
  5. public int compare(ListNode o1, ListNode o2) {
  6. if (o1.val < o2.val) return -1;
  7. else if (o1.val == o2.val) return 0;
  8. else return 1;
  9. }
  10. });
  11. ListNode dummy = new ListNode(0);
  12. ListNode p = dummy;
  13. for (ListNode node : lists) {
  14. if (node != null) queue.add(node);
  15. }
  16. while (!queue.isEmpty()) {
  17. p.next = queue.poll();
  18. p = p.next;
  19. if (p.next != null) queue.add(p.next);
  20. }
  21. return dummy.next;
  22. }

分治

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode mergeKLists(ListNode[] lists) {
  11. if (lists == null || lists.length == 0) return null;
  12. return merge(lists, 0, lists.length - 1);
  13. }
  14. private ListNode merge(ListNode[] lists, int left, int right) {
  15. if (left == right) return lists[left];
  16. int mid = left + (right - left) / 2;
  17. ListNode l1 = merge(lists, left, mid);
  18. ListNode l2 = merge(lists, mid + 1, right);
  19. return mergeTwoLists(l1, l2);
  20. }
  21. private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  22. if (l1 == null) return l2;
  23. if (l2 == null) return l1;
  24. if (l1.val < l2.val) {
  25. l1.next = mergeTwoLists(l1.next, l2);
  26. return l1;
  27. } else {
  28. l2.next = mergeTwoLists(l1,l2.next);
  29. return l2;
  30. }
  31. }
  32. }