当前位置:网站首页>合并K个已排序的链表
合并K个已排序的链表
2022-07-03 00:29:00 【Schuyler Hu】
问题
思路
由于代码形参是直接给了一个数组,因此可以把每个节点都当成一个链表,然后通过每两个节点合并,构成新的链表,再与下一个节点合并,就可以实现整体K个链表的合并。但是这种方法会超时,无法ac。因此采用从中间将数组一分为二,直到分成一个个单独节点。最后将单独节点连接起来,得到合并后的K个链表。
代码实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
return divMerge(lists, 0, lists.size() - 1);
}
// 将数组对半拆成一个个元素,再合并
ListNode* divMerge(vector<ListNode*> &lists, int left, int right)
{
if (left > right) return NULL;
if (left == right) return lists[left];
int mid = left + (right - left) / 2;
return mergeTwoList(divMerge(lists, left, mid), divMerge(lists, mid + 1, right));
}
// 合并两个链表
ListNode* mergeTwoList(ListNode* p1, ListNode* p2)
{
ListNode* ret = new ListNode(0);
ListNode* cur = ret;
while (p1 && p2)
{
if (p1->val < p2->val)
{
cur->next = p1;
p1 = p1->next;
}
else
{
cur->next = p2;
p2 = p2->next;
}
cur = cur->next;
}
if (p1)
{
cur->next = p1;
}
if (p2)
{
cur->next = p2;
}
return ret->next;
}
};
边栏推荐
- 关于QByteArray存储十六进制 与十六进制互转
- 世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
- Thread start and priority
- Lu Zhe, chief scientist of Shiping information: building data and personnel centered security capabilities
- Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
- Vulkan-实践第一弹
- Leetcode-2280: represents the minimum number of line segments of a line graph
- Shell implements basic file operations (SED edit, awk match)
- [AUTOSAR I overview]
- FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
猜你喜欢
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
指针进阶(一)
测试右移:线上质量监控 ELK 实战
[AUTOSAR + IO Architecture]
Vulkan practice first bullet
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
Vulkan performance and refinement
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
Unity learns from spaceshooter to record the difference between fixedupdate and update in unity for the second time
1.12 - 指令
随机推荐
Teach you JDBC hand in hand -- structure separation
The difference between relational database and non relational database
antv x6节点拖拽到画布上后的回调事件(踩大坑记录)
【AutoSAR 十三 NVM】
指针进阶(一)
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
2022.2.14 resumption
Thread start and priority
[AUTOSAR XIII NVM]
【AutoSAR 五 方法论】
How to systematically learn machine learning
[introduction to AUTOSAR seven tool chain]
Meaning of Tencent cloud free SSL certificate extension file
1.12 - 指令
[AUTOSAR II appl overview]
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
[AUTOSAR eight OS]
Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
RISA rz/g2l processor introduction | frame diagram | power consumption | schematic diagram and hardware design guide
Nacos+openfeign error reporting solution