力扣hot100 环形链表 快慢指针 哈希 数学公式

Problem: 142. 环形链表 II

文章目录

思路

👨‍🏫 参考题解

Code

⏰ 时间复杂度: O ( n ) O(n) O(n)

🌎 空间复杂度: O ( 1 ) O(1) O(1)

Java 复制代码
/**
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
	public ListNode detectCycle(ListNode head)
	{

		ListNode f = head;
		ListNode s = head;
		while (f != null && f.next != null)
		{
			f = f.next.next;
			s = s.next;
			if (f == s)// 到相遇点了
			{
				while (s != head)//两者相等即走到了入环点
				{
					s = s.next;// s 走 相遇点到入环点 的路
					head = head.next;// head 走 起点到入环点的路
				}
				return s;
			}
		}
		return null;
	}
}
相关推荐
圣保罗的大教堂9 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
Tisfy12 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
tkevinjd14 小时前
图论\dp 两题
leetcode·动态规划·图论
PyHaVolask17 小时前
链表基本运算详解:查找、插入、删除及特殊链表
数据结构·算法·链表
1白天的黑夜118 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼3519 小时前
力扣子集问题C++代码
c++·算法·leetcode
熬了夜的程序员19 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
Miraitowa_cheems19 小时前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
无聊的小坏坏1 天前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学