当前位置:网站首页>每日一题-合并K个升序链表-0722
每日一题-合并K个升序链表-0722
2022-08-05 05:17:00 【菜鸡程序媛】
题目
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
思路
- 采用归并排序的思路,先进行拆解到最小的单位,拆到不能再拆
- 然后再合并,合并成最终的链表
代码
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length <= 0)
return null;
return merge(lists, 0, lists.length - 1);
}
private ListNode merge(ListNode[] lists, int left, int right){
if(left == right)
return lists[left];
int mid = left + (right - left) / 2;
//为什么不是left,mid-1和mid,right呢,因为mid取得就是floor(value),如果-1的话,容易造出左侧越界
//拆解到最小的单位
ListNode l1 = merge(lists, left, mid);
ListNode l2 = merge(lists, mid + 1, right);
//进行合并,归并成最终的链表
return mergeTwoLists(l1, l2);
}
private ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null)
return l2;
if(l2 == null)
return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
边栏推荐
- 六、请求处理—获取请求参数系列注解是怎样工作的?
- HuiFer 带你读懂 BeanFactory getBean 方法
- 关于使用QML的MediaPlayer实现视频和音频的播放时遇到的一些坑
- 电子产品量产工具(2)- 输入系统实现
- Tensorflow steps on the pit notes and records various errors and solutions
- CVPR 2022 | 70% memory savings, 2x faster training
- PoE视频监控解决方案
- 基于STM32F407的一个温度传感器报警系统(用的是DS18B20温度传感器,4针0.96寸OLED显示屏,并且附带日期显示)
- You should write like this
- AIDL detailed explanation
猜你喜欢
随机推荐
【UiPath2022+C#】UiPath 循环
OSPF网络类型
Redis集群(docker版)——从原理到实战超详细
PoE视频监控解决方案
MySQL主从复制—有手就能学会的MySQL集群搭建教程
用GAN的方法来进行图片匹配!休斯顿大学提出用于文本图像匹配的对抗表示学习,消除模态差异!
Leetcode刷题——对链表进行插入排序
LeetCode刷题之第55题
Comparison and summary of Tensorflow2 and Pytorch in terms of basic operations of tensor Tensor
网络通信及相关函数介绍
GIS面试问题
(C语言)strlen、strcpy、strcat、strcmp、strstr函数的模拟实现
电子产品量产工具(1)- 显示系统实现
You should write like this
【shell编程】第三章:函数
十、视图解析原理与源码分析
关于存储IOPS你必须了解的概念
LeetCode刷题之第1024题
网管日记:故障网络交换机快速替换方法
CH32V307 LwIP移植使用









