当前位置: 首页 > news >正文

leetcode 23 合并K个升序链表

一、题目描述

二、解题思路

解法一:两两合并

整体思路

遍历lists向量,对每一个链表一一进行升序合并;

解法二:借助优先队列

借助优先队列(小根堆)来将判断结点的大小,每次弹出最小的结点,再进行尾插合并

三、代码实现

解法一:两两合并

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeKLists(vector<ListNode*>& lists) {//统计链表的个数int n=lists.size();//特殊情况处理if(n==0) return nullptr;if(n==1) return lists[0];//引入虚拟头节点ListNode* NewHead=new ListNode(0);for(auto l:lists)NewHead->next=my_merge(NewHead->next,l);//避免内存泄漏ListNode* ret=NewHead->next;delete NewHead;return ret;}ListNode* my_merge(ListNode* l1,ListNode* l2){//边界处理if(l1==nullptr) return l2;if(l2==nullptr) return l1;//虚拟头节点ListNode dmp(0);ListNode* NewHead=&dmp;ListNode* tail=NewHead;ListNode* cur1=l1;ListNode* cur2=l2;while(cur1&&cur2){if(cur1->val<=cur2->val){tail->next=cur1;cur1=cur1->next;}else{tail->next=cur2;cur2=cur2->next;}tail=tail->next;}//加上剩余的部分if(cur1) tail->next=cur1;if(cur2) tail->next=cur2;return NewHead->next;}
};

解法二:借助优先队列

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {struct cmp{bool operator()(const ListNode* l1,const ListNode* l2){return l1->val>l2->val;}};
public:ListNode* mergeKLists(vector<ListNode*>& lists) {//创建一个小根堆priority_queue<ListNode*,vector<ListNode*>,cmp> heap;//让所有头结点进入小根堆for(auto l:lists){if(l) heap.push(l);}//合并K个有序链表ListNode* ret=new ListNode(0);ListNode* prev=ret;while(!heap.empty()){ListNode* t=heap.top();heap.pop();prev->next=t;prev=t;if(t->next) heap.push(t->next);}prev=ret->next;delete ret;return prev;}
};

解法三:借助归并排序思想

http://www.dtcms.com/a/520020.html

相关文章:

  • Element Plus组件v-loading在el-dialog组件上使用无效
  • 广州骏域网站阿里云可以建设多个网站
  • 青海网站建设与制作网站做多长时间才会有流量
  • 金坛建设局网站网站建设的主要功能有哪些
  • UTB(Ultra-Thin Body)技术:原理、制造与未来展望
  • 【咨询】安卓开发语言选择分析(202510)
  • 兵团住房和城乡建设局网站做性的视频网站
  • 经典路径求解问题——路径之谜
  • AI大模型微调简介
  • Cesium绘制线:从基础到高级技巧
  • uniapp 实现网络测速小功能
  • RK Android14 添加了从产品配置中删除特定APK的功能
  • 恢复 git push -force 覆盖的提交记录
  • 自己做的网站怎么删除建设网站 无法显示图片
  • 黄冈网站ppt网站
  • AGV机器人
  • 面向对象——设计模式(创建型)
  • 05_逻辑回归
  • Dify从入门到精通 第25天 在 Dify 中构建智能天气查询机器人
  • 【设计模式】代理模式(Proxy)
  • 怎么建手机网站wordpress和公众号
  • ADS ERROR:invalid class id(0x71c)问题记录
  • 模板号专注于网站企业网站建设的类型
  • golang学习笔记:标准库slices
  • golang学习笔记:标准库os
  • Python机器学习---5.决策树
  • 恶劣天气目标检测IA-YOLO
  • Google Now in Android(NIA)
  • Flink中的Lookup join和Temporal join 的语法是一样的吗?
  • 网站建设和网站维护上海工商网上办事大厅电话