当前位置:网站首页>LeetCode:合并K个升序链表_23
LeetCode:合并K个升序链表_23
2022-06-28 20:59:00 【Yuyy】
思路
这题是21的升级版,从两路归并到多路归并,其中运用了优先队列来优化。感觉这题谈不上困难,只是运用了两个知识点,逻辑不复杂。
题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 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
Related Topics
- 链表
- 分治
- 堆(优先队列)
- 归并排序
- 1492
- 0
代码
public ListNode mergeKLists(ListNode[] lists) {
// 边界问题得注意
if (lists.length == 0) {
return null;
}
// 虚拟头节点
ListNode dummy = new ListNode();
ListNode p = dummy;
ListNode temp;
// 利用优先队列优化,不然每次都需要对所有头结点遍历,优先队列的好处就是可以动态的调整内部顺序
final Queue<ListNode> listNodes = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
for (ListNode listNode : lists) {
// 边界问题得注意
if (listNode == null) {
continue;
}
listNodes.offer(listNode);
}
// 多路归并
while ((temp = listNodes.poll()) != null) {
p.next = temp;
p = p.next;
if (temp.next != null) {
listNodes.offer(temp.next);
}
}
return dummy.next;
}Post Views: 162
边栏推荐
猜你喜欢

ThreadLocal principle

CNN-LSTM的flatten

ThreadLocal原理

Ehcache configuration data, convenient for self checking

with torch. no_ Grad(): reason for using

Win 10 create a gin framework project

openGauss内核分析之查询重写

我也差点“跑路”
![[learning notes] Introduction to principal component analysis](/img/24/a760d1cd095a967ef258b623eb465c.png)
[learning notes] Introduction to principal component analysis

Visualization of neural network structure in different frames
随机推荐
我也差点“跑路”
如何使用 DataAnt 监控 Apache APISIX
学习太极创客 — MQTT 第二章(七)ESP8266 MQTT 遗嘱应用
国产数据库名录一览
How do I download videos? Look at the super simple method!
RT-Thread线程同步与线程通信
How to do a good job in customer's successful bottom design | tob Master Course
输入和输出实型数据
新形势下的SaaS销售升级|ToB大师课
How to analyze the relationship between enterprise digital transformation and data asset management?
二叉树类题目 力扣
Input and output character data
The principle and source code analysis of Lucene index construction
Win 10 create a gin framework project
RT thread thread synchronization and thread communication
resilience4j 重试源码分析以及重试指标采集
Input and output real data
Real number operation
【学习笔记】因子分析
Ehcache configuration data, convenient for self checking