给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
示例 2:
输入:lists = [] 输出:[]
示例 3:
输入:lists = [[]] 输出:[]
提示:
k == lists.length0 <= k <= 10^40 <= lists[i].length <= 500-10^4 <= lists[i][j] <= 10^4lists[i]按 升序 排列lists[i].length的总和不超过10^4
package Solution23;
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(
(Comparator<? super ListNode>) new Comparator<ListNode>() {
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
ListNode head = new ListNode(0);
ListNode p = head;
for (ListNode list : lists) {
if (list != null)
queue.offer(list);
}
while (!queue.isEmpty()) {
ListNode n = queue.poll();
p.next = n;
p = p.next;
if (n.next != null)
queue.offer(n.next);
}
return head.next;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
public ListNode removeElements(ListNode head, int val) {
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return header.next;
}
void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
public static void main(String[] args) {
Solution sol = new Solution();
ListNode l1 = new ListNode(1);
l1.next = new ListNode(4);
l1.next.next = new ListNode(5);
ListNode l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
ListNode l3 = new ListNode(2);
l3.next = new ListNode(6);
// ListNode[] lists = new ListNode[] { l1, l2, l3 };
ListNode[] lists = new ListNode[] { null, l2 };
sol.printList(sol.mergeKLists(lists));
}
}
该博客介绍了如何将多个已排序的链表合并成一个有序链表。通过使用优先队列,实现了高效的时间复杂度和空间复杂度的解决方案。具体方法是创建一个最小堆,将每个链表的头节点放入堆中,然后每次取出最小节点作为新链表的节点,再将该节点的下一个节点放入堆中,直至所有节点处理完毕。
1081

被折叠的 条评论
为什么被折叠?



