LeetCode:M-142. Linked List Cycle II
来源:互联网 发布:各国语言在线翻译软件 编辑:程序博客网 时间:2024/06/10 15:57
LeetCode链接
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
1、快慢指针,如果快指针追上慢指针,则表示有环
1)快慢指针起始都是head
2)快指针每次走2步,慢指针每次走1步
3)经过k步,快指针追上慢指针
2、查找环的开始点
1)设head到环的开始位置的步长为s
2)设环的开始位置到快慢指针相遇点,经过步长m,则 k=s+m -> s=k-m
3)设环的长为r步长,则快慢相遇时 k+nr=2k -> k=nr
4)由2),s = k-m = nr - m = (n-1)r + (r-m),r-m为快慢相遇点到环起点的距离
5)从head和快慢相遇点同时开始遍历,head会走s步, 快慢相遇点会走 (n-1)r + (r-m)步,由于(n-1)r就是绕环,不影响两者的相遇,遍历的相遇点就是环的开始点
TC = O(n)
/** * 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) return null; ListNode slow=head; ListNode fast=head; boolean hasCycle=false; while(fast.next!=null && fast.next.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast){ hasCycle=true; break; } } if(hasCycle){ slow = head; while(slow != fast){ slow=slow.next; fast=fast.next; } return slow; } return null;}}
阅读全文
0 0
- LeetCode:M-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
- 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
- HDU 6159 cable cable cable
- EasyPlayerPro(Windows)开发之框架讲解
- Java注解详解
- UVa 699 The Falling Leaves
- 中山大学算法课程题目详解(第一周)
- LeetCode:M-142. Linked List Cycle II
- 【POJ3195】Generalized Matrioshkas(栈)
- (算法分析Week1)Different Ways to Add Parentheses[Medium]
- 三级联动
- 路径规划之A* 算法
- 一个简单的侧滑
- sqli-labs page-1
- MFC无法添加控件变量
- Leetcode327——Count of Range Sum