题目

合并K个升序列表 - 图1

解题思路

维护当前每个链表没有被合并的元素的最前面一个,k 个链表就最多有 k 个满足这样条件的元素,每次在这些元素里面选取 val 属性最小的元素合并到答案中。在选取最小元素的时候,可以用优先队列来优化这个过程。

代码

  1. class Solution {
  2. class Status implements Comparable<Status> {
  3. int val;
  4. ListNode ptr;
  5. Status(int val, ListNode ptr) {
  6. this.val = val;
  7. this.ptr = ptr;
  8. }
  9. public int compareTo(Status status2) {
  10. return this.val - status2.val;
  11. }
  12. }
  13. PriorityQueue<Status> queue = new PriorityQueue<Status>();
  14. public ListNode mergeKLists(ListNode[] lists) {
  15. for (ListNode node: lists) {
  16. if (node != null) {
  17. queue.offer(new Status(node.val, node));
  18. }
  19. }
  20. ListNode head = new ListNode(0);
  21. ListNode tail = head;
  22. while (!queue.isEmpty()) {
  23. Status f = queue.poll();
  24. tail.next = f.ptr;
  25. tail = tail.next;
  26. if (f.ptr.next != null) {
  27. queue.offer(new Status(f.ptr.next.val, f.ptr.next));
  28. }
  29. }
  30. return head.next;
  31. }
  32. }