[LeetCode]142. Linked List Cycle II
来源:互联网 发布:骁龙835支持5g网络吗 编辑:程序博客网 时间:2024/04/20 17:58
https://leetcode.com/problems/linked-list-cycle-ii/
从第一次相遇可得:slow: a + b; fast: 2(a + b). 并且2a + 2b = a + b + n(b + c), 可得a = (n - 1)b + nc,以此slow移到head,然后slow和fast都每次移动一位,最后相遇位置就是环开头。
/** * 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) { if (head == null || head.next == null) { return null; } ListNode fast = head.next.next; ListNode slow = head.next; while (fast != null && fast.next != null) { if (fast == slow) { break; } fast = fast.next.next; slow = slow.next; } if (fast == null || fast.next == null) { return null; } slow = head; // 这里fast也是每次移一位! while (fast != slow) { slow = slow.next; fast = fast.next; } return slow; }}
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- cURL实现Get和Post
- python多线程编程(5): 条件变量同步
- 【C#】C#winform 双击/按"F12"键全屏,按"Esc"键退出
- MVC, WEB MVC, SPRING MVC 图解
- 自我学习,监督学习,半监督学习和迁移学习的区别
- [LeetCode]142. Linked List Cycle II
- 基本的几个设计模式
- linux下配置maven运行环境
- spring mvc框架概述
- Maven的安装配置
- ngnix做Https访问设置及依据URL后缀分流访问
- mysql 优化--定位慢查询
- Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.lang.RuntimeException: Som
- 滑动RecyclerView时隐藏部分控件