leetcode fast slow pointer
来源:互联网 发布:襄阳网站搜索引擎优化 编辑:程序博客网 时间:2024/06/06 20:14
Introduction
In questions related to linked list, fast and slow pointer solution is very common. Fast pointer step two and Slow pointer step one. Always we can the regular through draw a picture and mathematical derivation, we can find:
- middle of the linked list
- interaction pointer to assert if there is a cycle
leetcode 141 Linked List Cycle
Question
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution
Only if there is a cycle, fast will catch up with the slow pointer.
class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ fast = head slow = head while fast != None and fast.next != None: fast = fast.next.next slow = slow.next if fast == slow: return True return False
leetcode 142 Linked List Cycle II
Question
Fast pointer catch up slow when slow is on the first cycle. so:
- slowLen = a + b
- fastLen = (a + b) + n*r
- fastLen = 2 * slowLen
- a + b + n*r = a +b +b +c + (n-1)r = 2 (a + b)
- c = a +( n - 1) * r
When they come across, slow from the head and fast from the meeting point, they will finally meet at the begin point of the cycle.
class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast = head slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: slow = head while fast != slow: fast = fast.next slow = slow.next return slow return None
0 0
- leetcode fast slow pointer
- (Leetcode)链表的slow,fast指针使用
- leetcode 用fast-slow 指针的方法判断链表是否为回文链表。
- TCP: slow start & congestion avoidance & fast retransmit & fast recovery
- Leetcode-Pointer Magic
- Friday Q&A 2013-10-11: Why Registers Are Fast and RAM Is Slow
- slow slow slow to increase
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- java牛人博客
- 在php页面中显示数据库内容时,中文显示乱码
- 关于Xcode 检查内存泄露方法
- linux命令之ls
- ResultSet转Json
- leetcode fast slow pointer
- android 可滑动、点击切换的导航栏
- 全屏滑动返回
- CXF动态客户端调用webservice实例
- gensim-5个学习阶段
- 个人整理的web开发中常用的表单验证的正则表达式JS
- Connection reset by peer原因
- 埃拉托色尼筛选算法
- Valid Parentheses