当前位置:网站首页>合并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;
}
};
边栏推荐
猜你喜欢
[AUTOSAR five methodology]

【C语言】分支和循环语句(上)

Rust ownership (very important)

Infrared thermography temperature detection system based on arm rk3568

Basic use of sringcloud & use of component Nacos

世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力

Vulkan practice first bullet

The difference between tail -f, tail -f and tail

How to convert Quanzhi a40i/t3 to can through SPI

Vulkan performance and refinement
随机推荐
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
Array common operation methods sorting (including ES6) and detailed use
Some introduction and precautions about XML
Thank you for being together for these extraordinary two years!
Hdu3507 (slope DP entry)
leetcode-871:最低加油次数
【AutoSAR 八 OS】
瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
Leetcode-934: the shortest Bridge
[daily training] 871 Minimum refueling times
指针进阶(一)
瑞萨RZ/G2L ARM开发板存储读写速度与网络实测
文件操作IO-Part2
[flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
Rust ownership (very important)
测试右移:线上质量监控 ELK 实战
Vulkan is not a "panacea"“
【AutoSAR 十二 模式管理】
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
The difference between tail -f, tail -f and tail