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
目录
相关文章
|
机器学习/深度学习 传感器 安全
【目标检测】基于背景差分实现运动车辆检测附Matlab代码
【目标检测】基于背景差分实现运动车辆检测附Matlab代码
SAP RETAIL 供应商寄售库存的UB STO(三)
SAP RETAIL 供应商寄售库存的UB STO(三)
SAP RETAIL 供应商寄售库存的UB STO(三)
|
机器学习/深度学习 人工智能 自然语言处理
人工智能检测技术在司法监督管理上的应用
在我国深化司法体制改革的时代背景下,为响应国家提高司法现代化水平,构建司法文明的要求,将人工智能引入法院的实践正如火如荼开展。人工智能的优势与法律的特点相契合,论证了司法与人工智能结合具备技术实现层面的可行性。而如何真正地将人工智能技术应用于司法领域却是摆在大家面前的真实挑战。本文中,阿里云智能 AI MVP,北京华夏电通发展规划总监王瑞宾为大家分享了人工智能检测技术在司法监督管理上的应用。
1195 0
人工智能检测技术在司法监督管理上的应用
|
前端开发 大数据 .NET
|
运维 Shell 网络安全
|
1天前
|
云安全 人工智能 安全
AI被攻击怎么办?
阿里云提供 AI 全栈安全能力,其中对网络攻击的主动识别、智能阻断与快速响应构成其核心防线,依托原生安全防护为客户筑牢免疫屏障。
|
11天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~