当前位置:网站首页>合并K个升序链表---2022/02/26
合并K个升序链表---2022/02/26
2022-06-11 17:18:00 【城猪猪】
题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
题目来源
解题思路
这里有两种解法可以考虑:
首先是队列优先。思路是,把所有链表的头节点放入优先队列中。(补充说明:优先队列与先进先出队列不一样,每次取出的是具有最高优先级的元素。默认情况下,优先队列元素按照自然顺序排序,即数字小的在队头,字符串则按字典序排序。如果需要改变优先级的设定,需要实现Comparator接口。)而后将节点值值最小(涉及到优先级重新设定)的节点弹出,添加到新建链表中,而后再将该节点的下一节点添加到队列,直至队列为空。
其次是分治法。也就是一分为二(做前后分处理)的思想,需要借助的函数时合并两个升序链表。分到不可分为止,然后递归。
本题采用队列优先的方法。
代码实现
代码实现如下:
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0) return null;
if(lists.length==1) return lists[0];
ListNode head=new ListNode(0);
ListNode cur=head;
PriorityQueue<ListNode> pq=new PriorityQueue<>(new Comparator<ListNode>() {
public int compare(ListNode o1,ListNode o2) {
return o1.val-o2.val;//做升序处理,小的在队头
// return o2.val-o1.val;//做升序处理,小的在队头
}
});
for(ListNode list:lists) {
if(list==null)continue;
pq.add(list);
}
while(!pq.isEmpty()) {
ListNode nextNode=pq.poll();
cur.next=nextNode;
cur=cur.next;
if(nextNode.next!=null) {
pq.add(nextNode.next);
}
}
return head.next;
}
性能评估

发现了一个迷惑的操作。重复提交代码,内存性能持续降低,而时间性能不受影响。
边栏推荐
- What problems are exposed when all Sohu employees are cheated?
- ffmpeg CBR精准码流控制三个步骤
- JPA failed to save multiple entities circularly
- Export data prompt -- solution to the problem of secure file priv option
- QLineEdit 设置输入掩码
- Cs0006 C failed to find metadata file "c:\users\... Problem
- 【线上问题】Timeout waiting for connection from pool 问题排查
- 05_ Feature Engineering - dimension reduction
- Config: user attribute configuration framework
- DFS和BFS笔记(一)基于C语言的广度优先搜索
猜你喜欢

DFS and BFS notes (I) breadth first search based on C language

ffmpeg奇偶场帧Interlace progressive命令和代码处理

Connect the server with springboard / fortress through xshell

Activity | authing's first channel cooperation activity came to a successful conclusion

Vscode configures eslint to automatically format an error "auto fix is enabled by default. use the single string form“

Chip mass production, oppo entering a new era?

Authing 双周动态:Authing 论坛上线(4.25-5.8)

如何成为一个乐观派组织?

活动 | Authing 首次渠道合作活动圆满落幕

vscode保存代码时自动eslint格式化
随机推荐
Use of forcescan in SQL server and precautions
leetcode--数组
Vscode configures eslint to automatically format an error "auto fix is enabled by default. use the single string form“
QLineEdit 设置输入掩码
From a "trendsetter" to a "wind chaser", can master Kang still lead the market?
Bentley 使用 Authing 快速实现应用系统与身份的集成
Global and China Mobile Network Optimization (MnO) industry development panoramic survey and Investment Strategy Research Report 2022-2028
LeetCode-859. 亲密字符串
Docker安装mysql5.7(开启binlog功能、修改字符)
你还不懂线程池的设计及原理吗?掰开揉碎了教你设计线程池
Typescipt Basics
LeetCode-384. 打乱数组
6-2 多个整数的逆序输出-递归
05_特征工程—降维
How to become an optimist organization?
Science popularization genius on the left, madman on the right
Port planning and APJ
括号生成---2022/02/25
Semaphore PV operation of process interaction and its code implementation
从制造到“智造”,探索制造企业破局之道