LeetCode-Linked List Cycle II
来源:互联网 发布:贤友板材优化软件 编辑:程序博客网 时间:2024/04/30 14:46
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24018961
时间:2014-4-19
题目
Linked List Cycle II
Total Accepted: 10764 Total Submissions: 35294My SubmissionsGiven a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
想法:
见《cracking the code interview》P126 中文版1.一个一步走的slow指针,一个两步走的fast指针
2.如果有环,slow 与fast 一定碰面(如果刚好错过,一定是错过一步(并且是fast(K+1)领先slow(K-1),K为环中从相交点开始计算的数字),但是,他们的上一步(均为k-1)正好相遇)
3.假设Fast走了2N步,那么slow走了N步。
如果环一共有M个节点,当
/** * 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 slow = head; ListNode fast = head; if(head == null || head.next == null) return null; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast) break; } if(fast == null || fast.next == null) return null; slow = head; while(slow != fast){ slow = slow.next; fast = fast.next; } return fast; }}
返回
LeetCode Solution(持续更新,java>c++)
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- 几句代码写出一个内容轮播器(jQuery插件的神奇)jQuery.flexslider.js登场!!
- 【Gapps】安装GooglePlay引发一系列问题
- UINavigationController中是否显示返回按钮
- 【WINDOWS】Locale ID (LCID) Chart
- 【boost】boost::bind的使用
- LeetCode-Linked List Cycle II
- Leetcode:Remove Duplicates from Sorted List II
- 内联(inline)函数和宏定义(#define)的区别
- 求一点在空间平面上的垂足
- 2014年亚洲值得关注的15家科技IPO
- Jquery dialog
- ld: symbol(s) not found for architecture armv7s
- LINUX内核中的xx_initcall初始化标号
- NOEO滤波器优化设计