给定一个链表数组,每个链表都已经按升序排列。
请将所有链表合并到一个升序链表中,返回合并后的链表。
解释:
PriorityQueue具有队列先入先出的特点,但优先级队列先通过一些方法对元素进行比较,最小的元素优先级最高,在访问或删除操作时只能对集合中优先级最高的元素进行。该队列不允许使用 null 元素也不允许插入不可比较的对象(没有实现Comparable接口的对象)。
示例 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.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
代码和测试如下:
package com.haijiao12138.demo.leetcode.九月刷题.test0903;
import java.util.*;
/**
* @author: haijiao12138
* @ClassName: 合并排序链表
* @description: TODO
* @date: 2021/9/3 16:33
*/
public class 合并排序链表 {
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
listNode1.next = listNode4;
listNode4.next = listNode5;
ListNode listNode11 = new ListNode(1);
ListNode listNode33 = new ListNode(3);
ListNode listNode44 = new ListNode(4);
listNode11.next = listNode33;
listNode33.next = listNode44;
ListNode listNode22 = new ListNode(2);
ListNode listNode66 = new ListNode(2);
listNode22.next = listNode66;
ListNode[] nodes = new ListNode[3];
nodes[0] = listNode1;
nodes[1] = listNode11;
nodes[2] = listNode22;
ListNode listNode = mergeKLists(nodes);
while (listNode!=null){
System.out.print(listNode.val+" ");
listNode = listNode.next;
}
}
public static ListNode mergeKLists(ListNode[] lists){
//边界考虑
if (lists.length == 0){
return null;
}
Queue<ListNode> heap = new PriorityQueue<>((ListNode a, ListNode b) -> (a.val - b.val));// 优先队列 先进先出
for (int i = 0; i < lists.length; i++) {
ListNode curHead = lists[i];
while (curHead != null){
heap.offer(curHead);//添加元素
curHead = curHead.next;
}
}
ListNode head = heap.poll();
ListNode node = head;
while (!heap.isEmpty()){
node.next = heap.poll();
node = node.next;
}
if (node != null)
node.next = null;
return head;
}
static class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
}
}
程序结果如下: