Q:合并k个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。
A:用小跟堆

public static ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists == null || lists.size() == 0)
            return null;
        PriorityQueue<ListNode> q = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode node1, ListNode node2) {
                if (node1.val <= node2.val)
                    return -1;
                else
                    return 1;
            }
        });
        ListNode head0 = new ListNode(Integer.MIN_VALUE);
        ListNode curr = head0;
        for (ListNode node : lists) {
            ListNode node1;
            while (node != null) {
                node1 = node.next;
                node.next = null;
                q.add(node);
                node = node1;
            }
        }
        while (!q.isEmpty()) {
            curr.next = q.poll();
            curr = curr.next;
        }
        return head0.next;
    }

相关文章:

  • 2021-04-13
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
猜你喜欢
  • 2022-12-23
  • 2021-06-09
  • 2021-09-10
  • 2022-01-27
  • 2022-12-23
  • 2021-11-15
  • 2021-12-06
相关资源
相似解决方案