当前位置:网站首页>Merge K sorted linked lists
Merge K sorted linked lists
2022-07-03 01:01:00 【Schuyler Hu】
problem
Ideas
Because the code parameter is directly given to an array , Therefore, each node can be regarded as a linked list , Then merge every two nodes , Form a new linked list , Merge with the next node , You can achieve the whole K A combination of linked lists . But this method will time out , unable ac. Therefore, the array is divided into two from the middle , Until it is divided into individual nodes . Finally, connect the individual nodes , Get the merged K A linked list .
Code implementation
/** * 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);
}
// Split the array in half into elements , Re merger
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));
}
// Merge two linked lists
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;
}
};
边栏推荐
猜你喜欢
excel IF公式判断两列是否相同
拥抱平台化交付的安全理念
First hand evaluation of Reza electronics rz/g2l development board
【AutoSAR 一 概述】
[AUTOSAR nine c/s principle Architecture]
【AutoSAR 七 工具链简介】
Rust string slicing, structs, and enumeration classes
Win10 can't be installed in many ways Problems with NET3.5
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
随机推荐
【日常训练】871. 最低加油次数
leetcode-224:基本计算器
【AutoSAR 八 OS】
File operation io-part2
深度剖析数据在内存中的存储
lex && yacc && bison && flex 配置的問題
FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
Initial order of pointer (basic)
线程的启动与优先级
Vulkan-实践第一弹
鏈錶內指定區間反轉
1.12 - 指令
安全运营四要素之资产、脆弱性、威胁和事件
百度智能云牵头打造智能云综合标准化平台
MySQL multi table joint deletion
【AutoSAR 一 概述】
[case sharing] let the development of education in the new era advance with "number"
[shutter] image component (configure local GIF image resources | load placeholder with local resources)
Rust ownership (very important)
【AutoSAR 三 RTE概述】