zoukankan      html  css  js  c++  java
  • leetcode 【 Linked List Cycle 】 python 实现

    题目

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    代码:oj在线测试通过 Runtime: 416 ms

     1 # Definition for singly-linked list.
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     # @param head, a ListNode
     9     # @return a boolean
    10     def hasCycle(self, head):
    11         if head is None or head.next is None:
    12             return False
    13         
    14         p1 = ListNode(0)
    15         p1.next = head
    16         p2 = ListNode(0)
    17         p2.next = head
    18         
    19         result = False
    20         while p1 is not None and p2 is not None:
    21             if p1 == p2:
    22                 result = True
    23                 break
    24             else:
    25                 p1 = p1.next
    26                 p2 = p2.next
    27                 if p2 is not None:
    28                     p2 = p2.next
    29         
    30         return result

    思路

    这是一道经典的题 关键点是快慢指针

    p1是慢指针,一次走一步;p2是快指针,一次走两步;如果有循环,则快慢指针一定会在某一时刻遇上。

    有个问题比较关键:为啥进入循环后,快指针一定能在某一时刻跟慢指针踩在同一个点儿上呢?

    小白觉得可以如下解释:

    假设现在快慢指针都在循环当中了,由于循环是个圈,则可以做如下的等价:“慢指针一次走一步,快指针一次走两步” 等价于 “慢指针原地不动,快指针一次走一步”这个其实跟物理学中的相对运动原理差不多。

    欢迎高手来拍砖指导。

  • 相关阅读:
    Mybatis3.2和Spring3.x整合----Myb…
    Mybatis3.2和Spring3.x整合----Myb…
    支持向量分类方法
    KKT了解
    机器学习实战笔记 logistic回归
    朴素贝叶斯进行分类
    决策树算法实现
    KNN算法
    Spring AOP中增强知识
    Java动态代理知识
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4186965.html
Copyright © 2011-2022 走看看