leetcode fast slow pointer

简介: IntroductionIn questions related to linked list, fast and slow pointer solution is very common.

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

cycle
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

cycle
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
目录
相关文章
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
53 0
|
算法 Java
回溯算法详解(Back Tracking)
回溯算法详解(Back Tracking)
201 0
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
42 0
|
Java
什么是fail-fast
什么是fail-fast
76 0
LeetCode 383. Ransom Note
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
82 0
LeetCode 383. Ransom Note
LeetCode之Ransom Note
LeetCode之Ransom Note
127 0
|
安全 Java 应用服务中间件
深入理解Java中的fail-fast和fail-safe
什么是快速失败(fail-fast)和安全失败(fail-safe)?它们又和什么内容有关系。以上两点就是这篇文章的内容,废话不多话,正文请慢用。
1822 0
[LeetCode]--383. Ransom Note

Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can
1339 0