当前位置:网站首页>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
边栏推荐
- T-test (test whether the mean difference between the two populations is significant)
- 不同框架的绘制神经网络结构可视化
- Leetcode daily question - 522 Longest special sequence II
- 数据资产为王,如何解析企业数字化转型与数据资产管理的关系?
- Explanation of memory dump triggered by software watchdog and anr
- ANR无响应介绍
- LeetCode每日一题——515. 在每个树行中找最大值
- Real number operation
- 大智慧上怎么进行开户啊, 安全吗
- 新形势下的SaaS销售升级|ToB大师课
猜你喜欢

Data standardization processing

Ref attribute, props configuration, mixin mixing, plug-in, scoped style

mysql-发生系统错误1067

LeetCode每日一题——515. 在每个树行中找最大值

数据资产为王,如何解析企业数字化转型与数据资产管理的关系?

The further application of Li Kou tree

postman简介与安装步骤

Analysis of variance

Learning Tai Chi Maker - mqtt Chapter II (VII) esp8266 mqtt Testament application

I almost ran away
随机推荐
The blocks problem (uva101) Purple Book p110vector application
[graduation season · advanced technology Er] hard work can only pass, hard work can be excellent!
ANR无响应介绍
LeetCode每日一题——515. 在每个树行中找最大值
Employee salary management system
Is the inter-bank certificate of deposit reliable and safe
题解 Pie(POJ3122)超详细易懂的二分入门
1. integrate servlets
题解 Ananagrams(UVa156)紫书P113map的应用
力扣树的进一步应用
Leetcode daily question - 324 Swing sort II
新形势下的SaaS销售升级|ToB大师课
Ref attribute, props configuration, mixin mixing, plug-in, scoped style
GlobalSign的泛域名SSL证书
市值1200亿美金,老牌财税巨头Intuit是如何做到的?
题解 Andy s First Dictionary(UVa10815)紫书P112set的应用
阿里云 MSE 基于 Apache APISIX 的全链路灰度方案实践
Leetcode daily question - 522 Longest special sequence II
Please allow the "imperfection" of the current domestic Tob
Characters and integers