当前位置:网站首页>Force buckle 160. intersecting linked list
Force buckle 160. intersecting linked list
2022-07-27 06:07:00 【The last tripod】
Portal : Intersecting list
Their thinking
Because the intersection of the two linked lists must be y shape , So the overlapped parts of the two intersecting linked lists must be of equal length , The length difference is in the disjoint part in front of the two linked lists , Therefore, we can judge the length difference between the two linked lists in advance , Let the long linked list take the steps of difference first , After that, double pointers can traverse at the same time to determine whether they coincide
Code
/** * 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;
}
}
- Time complexity O(m+n)
- Spatial complexity O(1)
边栏推荐
猜你喜欢

What has been updated in the Chinese version of XMIND mind map 2022 v12.0.3?
Acwing the number of square arrays of one question per day

2022.6.10 STM32MP157串口时钟的学习

2021-06-26

根据SQL必知必会学习SQL(MYSQL)

pycharm安装及导入项目注意事项

韦东山 数码相框 项目学习(四)简易的TXT文档显示器(电纸书)

C语言扫雷最新 递归展开 超详解(附源码)

geonode geoserver win10 安装教程(亲测)

剪枝-量化-转onnx中文系列教程
随机推荐
编程学习记录——递归解决汉诺塔问题
Baiwen driving Daquan learning (II) I2C driving
Callback uses lambda
System Design的相关准备材料
What tools are needed to make video post effects?
socket编程一:使用fork()实现最基础的并发模式
常见的SQL优化方法
1 semi automatic crawler
c语言-线性顺序表
arcgis for js api-入门系列
Gbase 8C - SQL reference 6 SQL syntax (14)
Essential tool for making video special effects: nuke 13
韦东山 数码相框 项目学习(四)简易的TXT文档显示器(电纸书)
【动态规划----钢条切割问题】
【Arduino】重生之Arduino 学僧(1)
力扣题解 二叉树(8)
力扣题解 动态规划(3)
[first song] rebirth of me in py introductory training (4): Circular program
Super remote connection management tool: Royal TSX
Speech and Language Processing (3rd ed. draft) Chapter 2 ——正则表达式,文本归一化,编辑距离 阅读笔记