当前位置:网站首页>合并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;
}
};
边栏推荐
- University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
- Arduino开发之按键检测与正弦信号输出
- 12_微信小程序之微信视频号滚动自动播放视频效果实现
- 1.11 - 总线
- leetcode-224:基本计算器
- Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
- leetcode-2115:从给定原材料中找到所有可以做出的菜
- 如何系统学习机器学习
- 全志A40i/T3如何通过SPI转CAN
- 文件操作IO-Part2
猜你喜欢
【AutoSAR 八 OS】
研发一款国产ARM智能边缘计算网关需要什么
Liad: the consumer end of micro LED products is first targeted at TVs above 100 inches. At this stage, it is still difficult to enter a smaller size
【AutoSAR 十二 模式管理】
Use Jenkins II job
First hand evaluation of Reza electronics rz/g2l development board
[AUTOSAR II appl overview]
2022上半年值得被看见的10条文案,每一句都能带给你力量!
指针进阶(一)
瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
随机推荐
[AUTOSAR II appl overview]
Leetcode 294. Flip game II (game theory)
如何系统学习机器学习
1.11 - bus
MySQL multi table joint deletion
Reading and writing speed of Reza rz/g2l arm development board storage and network measurement
测试右移:线上质量监控 ELK 实战
matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
利亚德:Micro LED 产品消费端首先针对 100 英寸以上电视,现阶段进入更小尺寸还有难度
Arduino开发之按键检测与正弦信号输出
There is an unknown problem in inserting data into the database
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
【AutoSAR 四 BSW概述】
Teach you JDBC hand in hand -- structure separation
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
研发一款国产ARM智能边缘计算网关需要什么
【AutoSAR 十二 模式管理】
解决ReactNative使用webView存在缓存问题
Leetcode-1964: find the longest effective obstacle race route to each position
【日常训练】871. 最低加油次数