当前位置:网站首页>力扣160. 相交链表
力扣160. 相交链表
2022-07-27 05:21:00 【最后一只三脚兽】
传送门:相交链表
解题思路
由于两链表相交必然为y形,所以两个相交链表的后面重合部分一定是长度相等的,长度差别就在两链表前面的不相交部分,因此我们可以提前判断两链表的长度差值,让长链表先走差值的步数,之后双指针同时遍历判断是否重合即可
代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lenA=0;
int lenB=0;
ListNode nodeA = headA;
ListNode nodeB = headB;
while(nodeA != null){
lenA++;
nodeA = nodeA.next;
}
while(nodeB != null){
lenB++;
nodeB = nodeB.next;
}
ListNode longer = headA;
ListNode shorter = headB;
int diff = lenA - lenB;
if(lenA < lenB){
longer = headB;
shorter = headA;
diff = lenB - lenA;
}
while(diff-- > 0){
longer = longer.next;
}
while(longer != null && shorter != null){
if(longer == shorter){
return longer;
}
longer = longer.next;
shorter = shorter.next;
}
return null;
}
}
- 时间复杂度 O(m+n)
- 空间复杂度 O(1)
边栏推荐
- Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis
- 19. Up and down sampling and batchnorm
- Live Home 3D Pro室内家居设计工具
- [song] rebirth of me in py introductory training (8): module
- 【头歌】重生之我在py入门实训中(9):异常处理
- 18. Convolutional neural network
- geonode geoserver win10 安装教程(亲测)
- 6. Dimension transformation and broadcasting
- 根据SQL必知必会学习SQL(MYSQL)
- 14. Example - Multi classification problem
猜你喜欢

Pix2Pix原理解析

物联网操作系统多任务基础

视觉横向课题bug1:FileNotFoundError: Could not find module ‘MvCameraControl.dll‘ (or one of it

Lightroom classic 2022 v11.4 Chinese version "latest resources"

面试常问Future、FutureTask和CompletableFuture

14. Example - Multi classification problem

IOT operating system

Day 3. Suicidal ideation and behavior in institutions of higher learning: A latent class analysis

李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22

Greedy high performance neural network and AI chip application research and training
随机推荐
编程学习记录--第2课【初识C语言】
【头歌】重生之我在py入门实训中(10): Numpy
物联网操作系统
pytorch使用data_prefetcher提升数据读取速度
Multi task foundation of IOT operating system
13. Logistic regression
Dpdk network protocol stack VPP OVS DDoS Sdn nfv virtualization high performance expert Road
Essential tool for making video special effects: nuke 13
使用-Wall清除代码隐患
C language - linear sequence table
小技巧-彻底删除U盘中的文件
常见的SQL优化方法
arcgis for js api-入门系列
【头歌】重生之我在py入门实训中(4):循环程序
Auto Encoder(AE),Denoising Auto Encoder(DAE), Variational Auto Encoder(VAE) 区别
【头歌】重生之我在py入门实训中(5):列表
STM32-FSMC外扩内存SRAM
【头歌】重生之我在py入门实训中(12):Matplotlib接口和常用图形
C语言-文件操作
李宏毅 2020 深度学习与人类语言处理 DLHLP-Conditional Generation by RNN and Attention-p22