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;
}