给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
public class ListNode {
private int val;
private ListNode next;
public ListNode mergeKLists(ListNode[] lists) {
Queue<Node> queue = new PriorityQueue<Node>();
for (ListNode list : lists) {
if (list != null) {
queue.add(new Node(list.val, list));
}
}
ListNode head = new ListNode();
ListNode tail = head;
while (!queue.isEmpty()) {
Node min = queue.poll();
tail.next = min.node;
tail = tail.next;
if (min.node.next != null) {
queue.add(new Node(min.node.next.val, min.node.next));
}
}
return head.next;
}
class Node implements Comparable<Node> {
private int val;
private ListNode node;
public Node(int val, ListNode node) {
this.val = val;
this.node = node;
}
public int compareTo(Node o) {
return this.val - o.val;
}
}
}
时间复杂度:k*n*logk。k是指链表数组的个数。n是指每个链表的长度k*n表示每个节点都要被遍历一次。logk表示优先队列增加、删除节点后调整的时间复杂度。
空间复杂度:k。优先队列中元素的个数。
硬广告
欢迎关注公众号:double6