【Leetcode】Intersection of Two Linked List

CE基础入门:游戏内存修改与脚本开发实战指南 内存扫描是计算机程序调试和逆向工程中的基础技术,通过实时监控进程内存数据来理解程序运行机制。其原理基于现代计算机将所有运行时数据存储在内存中,每个数据都有唯一的内存地址标识。这项技术的核心价值在于帮助开发者分析软件内部数据结构,调试程序逻辑,并开发自动化工具。在游戏开发、软件测试和安全研究等领域有广泛应用。以Cheat Engine(CE)为代表的工具实现了高效的内存扫描与修改功能,支持指针寻址、多级偏移计算等高级特性。通过精确的数值类型识别和扫描策略优化,可以有效定位游戏中的血量、金币等关键数据,为游戏脚 阅读详情

【题目】:

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

【思路】

其实也是看了别人的想法,才试着实现了。

两个list,找共同的部分的开头,问题是,不知道长度,记录不了位置,所以不知道走到哪里才能比较

怎么样才能让两个list的指针同步呢?

答案就是,两个list “相加”,两个指针分别从l1 , l2开始 走到l2 ,l1 ,这样两个指针每次都增加一个,然后走的总共长度相同,而且最后几位,如果有相同的,一定是相等的!


 L1 : 1 ->2 ->3 ->4-X->X->X

L2 : 5->6-> X ->X->X


L1 + L2  : 1 ->2 ->3 ->4->X->X->X ->5->6-> X ->X->X

L2 +L1 :    5->6-> X ->X->X->1 ->2 ->3 ->4->X->X->X


但是实现起来还是有许多细节需要考虑:

比如p1, p2 走到l1,l2终点的时候怎么衔接,另外只能衔接一次,不能无限循环,所以要设定一个flag,如果衔接过一次,就不能再次衔接了。

而且因为l1 ,l2的长度不相等,指不定p1,p2谁先衔接,如果p1先到衔接点,要在判断一下p2的状况!!如果也要衔接了,就衔接, 如果不要的话,正常加一,然后continue!!到下一循环,因为两个点都已经更新了!!对于p2,vice versu, 所以写了两个大判断,每一个里面包含对另一个的判断。感觉应该会有更优化的结果。

如果都不是衔接点,那就是正常+1.

如果相等了,那么就return p1, p2随便哪个点。

如果循环都结束了还没有找到,那么就是return null


【我提交并且通过的代码】

Runtime: 337 ms

java里面中等水平吧,哈哈,还不错~

/**
 * 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) {
ListNode l1 = headA;
		ListNode p1 = headA;
		
		ListNode l2 = headB;
		ListNode p2 = headB;
		
		boolean flag1 = true;
		boolean flag2 = true;
		
		while(p1!=null && p2 != null){
			if (p1 == p2) return p2;
			
			else{
				if(p1.next==null && flag1 == true) {
					p1 = l2;
					flag1 = false;
					if(p2.next == null && flag2 == true) {
						p2 = l1;
						flag2 = false;
						continue;
					}
					p2 = p2.next;
					continue;
					
				}
				if(p2.next==null && flag2 ==true) {
					p2 = l1;
					flag2 = false;
					if(p1.next==null && flag1 == true) {
						p1 = l2;
						flag1 =false;
						continue;
					}
					p1 = p1.next;
					continue;
				}
				p1 = p1.next;
				p2 = p2.next;
			}
			
		}
		return null;
    }
}


【官方答案】

There are many solutions to this problem:

  • Brute-force solution (O(mn) running time, O(1) memory):

    For each node ai in list A, traverse the entire list B and check if any node in list B coincides with ai.

  • Hashset solution (O(n+m) running time, O(n) or O(m) memory):

    Traverse list A and store the address / reference to each node in a hash set. Then check every node bi in list B: if bi appears in the hash set, then bi is the intersection node.

  • Two pointer solution (O(n+m) running time, O(1) memory):
    • Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
    • When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A.
    • If at any point pA meets pB, then pA/pB is the intersection node.
    • To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
    • If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.
貌似是一个想法!

看到的更优的解法:

思路是一致的,但是分开单独处理的p1,p2,貌似见过,不错!这次一定要记住!

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode A = headA;
    ListNode B = headB;
    int times = 0;
    while(times<=1){
        if(A==B)
          return A;
        if(A==null){
            A=headB;
            times++;
        }
        else
          A=A.next;
        if(B==null)
          B=headA;
        else
          B=B.next;              


    }
    return null;
}

Runtime: 352 ms


用hashset 的做法:

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        HashSet<ListNode> set = new HashSet<ListNode>();
        while(headA!=null||headB!=null){
            if(headA!=null) {
                if(set.contains(headA)){
                    return headA;
                } else {
                    set.add(headA);
                }
                headA=headA.next;
            }

            if(headB!=null) {
                if(set.contains(headB)) {
                    return headB;
                } else {
                    set.add(headB);
                }
                headB=headB.next;
            }
        }
        return null;

    }
}



Abaqus子程序开发避坑指南:从UMESHMOTION到齿轮磨损分析实战 本文深入探讨Abaqus子程序开发中的关键技术与避坑指南,重点解析UMESHMOTION在齿轮磨损分析中的实战应用。从开发环境搭建、调试框架构建到性能优化和大规模计算,提供系统化的解决方案。通过真实案例展示如何避免内存泄漏、网格畸变等常见问题,并介绍数据驱动的磨损预测等前沿技术,帮助工程师提升仿真精度与效率。 阅读详情

相关推荐

ADS2023实战:2.4GHz超外差接收机从设计到链路预算全流程解析

本文以ADS 2023软件为平台,详细解析了2.4GHz超外差接收机从核心指标定义、架构原理到完整链路搭建与仿真的全流程。通过实战演练,重点阐述了如何利用ADS进行谐波平衡仿真和链路预算分析,以量化评估系统增益、噪声系数等关键性能,为射频工程师提供了一套从理论到仿真的系统级设计方法。

herb5的博客 830

【Leetcode】 Intersection of two linked list

Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘

ljffdream的专栏 459

基于Ventoy制作单个U盘引导Windows+Linux+黑苹果macOS

一款国内高手开发的一个名为Ventoy的开源多系统启动U盘制作工具,官方链接:https://www.ventoy.net/cn/index.html Ventoy 特点 不影响U盘日常普通使用 直接从ISO文件启动,无需解开 支持MBR和GPT分区格式(1.0.15+) 支持超过4GB的ISO文件 支持大部分常见操作系统, 已测试650+ 个ISO文件 不仅仅是启动,而是完整的安装过程 版本升级时数据不会丢失 Ventoy 待改进 不支持macOS和ChromeOS 准备2个空的U.

wybarcelona的博客 3万+

[leetcode][list] Intersection of Two Linked Lists

题目: Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘

Clairezz_的博客 320

COMSOL实战:薄膜声学超材料模态分析全流程解析(含预应力设置技巧)

本文详细解析了使用COMSOL进行薄膜声学超材料模态分析的全流程,包括预应力设置技巧和共振频率优化方法。通过实际案例和参数设置指南,帮助工程师掌握从几何建模到结果解读的关键步骤,特别适合声学超材料和共振薄膜结构的设计与优化。

ujm5678901的博客 304

HyperLynx(十四)高级分析技术

如果没有查找到该模型,可使用菜单命令“Setup”→“Options”→“Directories”,打开“Set Directories”对话框,单击“Edit”按钮,在“Select Directories for IC-Model Files”对话框中将路径“…在“Assign Models”对话框中的“Port”栏找到“OUTM”端口,在其对应的“Circuit Connection”栏中选择“txout”项。将端口R75连接到“Gnd”。同样,将“EMP”连接到“V”,完成预加重设置。...

小幽余生不加糖 4967

LeetCode之Intersection of two linked list不同方法

AC完看答案发现答案超简单,而自己的方法有点过于复杂了,题目原意是找出两个链表第一个公共节点,如果没有则返回NULL。 看到题目后,我竟然想到可能存在交叉结构,结果通过反转一个链表来求出是否存在公共节点,但是却没法求出第一个公共节点,因此重新看回题目,发现根本不可能有交叉结构嘛,这是链表啊,一个节点怎么可能有多个next节点呢,两个链表如果有公共节点,其尾节点必然相同。不过,既然已经写了那么多了

xanxus46的专栏 731

python实现纵横向拉开档次法 (附完整源码)

python实现纵横向拉开档次法 (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 791

LeetCode---Linked List Cycle、Linked List Cycle II、Intersection of Two Linked Lists

141.Linked List Cycle Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integerposwhich represents the position (0-indexed)in the l...

qq_27318693的博客 249

【unity实战】完美的2D横版平台跳跃玩家控制器,使用InputSystem+有限状态机实现人物加速减速 多段跳 长短跳 多段攻击 冲锋 冲锋残影 滑墙 蹬墙跳 滑墙 土狼时间 预输入 攀爬 爬楼梯

【unity实战】使用unity的新输入系统InputSystem+有限状态机设计一个玩家状态机控制——实现玩家的待机 移动 闪避 连击 受击 死亡状态切换这次来实现一个2d平台平台跳跃玩家控制器,平台人物控制要做的好,要考虑的问题会有很多,比如移动加速减速 多段跳 冲锋 冲锋残影 滑墙 蹬墙跳 土狼时间 预输入 攀爬 爬楼梯//减速至于为什么叫这个名字(土狼时间)呢?其实这个名词来自于华纳兄弟动画公司,一部古老的动画系列影片《Looney Tunes》

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 6060

【微信小程序】微信小程序开发环境搭建:安装微信小程序开发者工具

通过本文的介绍,你应该已经成功安装并配置了微信小程序开发者工具,为微信小程序开发做好了准备。接下来,你可以开始编写你的第一个小程序项目,探索更多有趣的功能和特性。祝你开发顺利,创造更多优秀的作品!

墨夶的博客 2994

LeetCode 160 Intersection of Two Linked Lists(链表相交)(Linked List)(*)

翻译写一个程序来找出两个单链表相交的开始处。例如,如下有两个链表:在节点c1处开始相交。批注: 如果两个链表根本没有相交,返回NULL。 在函数返回后链表必须保留原有的数据结构。 你可以假设在整个链结构中没有循环。 你的代码最后可以在O(n)时间和O(1)空间运行。原文Write a program to find the node at which the intersection of two

nomasp 8187

Pytorch实用教程:super(MLP,self).__init__()和super().__init__()有什么区别?

在 Python 中,super()函数用于调用父类(超类)的方法。它的使用在继承关系中非常常见,特别是在初始化继承自父类的属性时。在 PyTorch 中,这通常见于初始化nn.Module类的子类。super()的两种调用方式有微妙的差别,但在 Python 3 中常常用来达到同样的目的。这种写法在 Python 2 中非常常见。这里,super()被调用时需要指定当前类名(MLP)和当前实例(self。

若北辰 1032

LeetCode[Linked List]: Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins. Notes: If the two linked lists have no intersection at all, return null.The linked lists must retain t

chfe910的专栏 771

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

LeetCode C++ 160. Intersection of Two Linked Lists【Linked List/Two Pointers】简单

Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to intersect at node c1. Example 1: Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skip

memcpy0的博客 371

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

intersection of two linked list|leetcode c++

about this problem, 1.calculate the precise length of the two linked list. 2.calculate the difference value of two length of the linked list. then move the head node difference value of steps behin

wishingweed 482

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Intersection of Two Linked List ---LeetCode

https://leetcode.com/problems/intersection-of-two-linked-lists/解题思路:方法一利用两个表长度的差值,让长的链表先走,直到两个链表长度相等。接着两个表都一步一步走,如果碰头就 return。/** * Definition for singly-linked list. * public class ListNode { *

likexin的博客 359

【LeetCode】25.Linked List —Intersection of Two Linked Lists 链表-两个链表的交集

Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: begin to intersect at node c1. Example 1: ...

weixin_30451709的博客 183

leetcode--160 intersection of two linked list

Write a program to find the node at which the intersection of two singly linked lists begins.For example, the following two linked lists:A: a1 → a2 ↘

evolone的专栏 480

Leetcode_Linked_List --160. Intersection of Two Linked Lists [easy]

Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ ...

Ling的博客 244

Day04: LeetCode. Linked List: 24, 19, 160, 142

Day04: LeetCode. Linked List: 24, 19, 160, 142

dan_dan_burger的博客 1914

160. Intersection of Two Linked Lists leetcode (list)

Intersection of Two Linked Lists Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists:A: a1 → a2

shanshanhi的博客 467

Leetcode日练笔记30 [Linked List专题] #142 #160 Linked List Cycle II & Intersection of Two Linked Lists

Leetcode 链表专题 #142 Linked List Cycle II #160 Intersections of two Linked List (Python解法)

Bittersweet_t的博客 186

leetcode-160- 相交链表(intersection of two linked list)-java

题目及测试 package pid160; /* 相交链表 编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → ...

今天吃了吗的博客 385

LeetCode - 141. Linked List Cycle & 160. Intersection Of Two Linked Lists(链表成环问题)

LeetCode141 Linked List Cycle &amp;amp;amp;amp; 142 Linked List Cycle II &amp;amp;amp;amp;160 Intersection Of Two Linked Lists LeetCode141 Linked List Cycle(判断是否有环) LeetCode142 Linked List Cycle II(找到第一个入环节点) LeetCode160 ...

zxzxin的博客~ 341

leetcode刷题系列----模式2(Datastructure 链表)- 160:Intersection of Two Linked List 相交链表

leetcode刷题系列----模式2(Datastructure 链表)- 160:Intersection of Two Linked List 相交链表 Tips 更多题解请见本系列目录 此链表问题可以使用双指针解决,注意算法的复杂度为O(m+n),意味着2*(m+n)次遍历也属于该时间复杂度,不可狭隘的认为仅仅遍历m+n次链表节点。 双指针确实是一个很大的算法思想类。 Python # Definition for singly-linked list. # class ListNode: #

My_Communication的博客 967
上一篇: 【Java网络】STMP邮件协议 发送客户端
下一篇: 【Leetcode】 Intersection of two linked list
ljffdream
博客等级 码龄15年 4粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值