1.题目描述
给定一个链表数组,每个链表都已经按升序排列。
请将所有链表合并到一个升序链表中,返回合并后的链表。
示例 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
2.解题思路
由于k个链表都已经有序,我们借助优先队列中的小根堆可以很容易实现本题要求。先把K个链表的首个结点加入到优先队列中,根节点就是小根堆中最小的那个结点,当根节点被弹出时,如果它的next不为空,就把它的next结点加入到队列中,这样依次被弹出的结点就是一个按照升序排列的序列,只需要将它们串在一个链表中即可。
3.代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
Comparator<ListNode> comparator = new Comparator<ListNode>() {
@Override
public int compare(ListNode t0, ListNode t1) {
if (t0.val > t1.val) {
return 1;
} else if (t0.val < t1.val) {
return -1;
} else {
return 0;
}
}
};
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> queue = new PriorityQueue<>(comparator);
for (ListNode x : lists) {
if (x != null) {
queue.offer(x);
}
}
ListNode head = null, tail = null;
while (!queue.isEmpty()) {
ListNode cur = queue.poll();
if (cur.next != null) {
queue.offer(cur.next);
}
if (head == null) {
head = cur;
tail = head;
} else {
tail.next = cur;
tail = tail.next;
}
}
return head;
}
}