https://leetcode-cn.com/problems/merge-k-sorted-lists/submissions/

小根堆

  1. public static class ListNode {
  2. int val;
  3. ListNode next;
  4. ListNode() {}
  5. ListNode(int val) { this.val = val; }
  6. ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  7. }
  8. public ListNode mergeKLists(ListNode[] lists) {
  9. PriorityQueue<ListNode> heap = new PriorityQueue<>((ListNode l1, ListNode l2) -> {
  10. return l1.val - l2.val;
  11. });
  12. for (ListNode list : lists) {
  13. if (list != null) {
  14. heap.offer(list);
  15. }
  16. }
  17. ListNode head = new ListNode(0);
  18. ListNode cur = head;
  19. while (!heap.isEmpty()) {
  20. cur = cur.next = heap.poll();
  21. if (cur.next != null) {
  22. heap.offer(cur.next);
  23. }
  24. }
  25. cur.next = null;
  26. return head.next;
  27. }