zoukankan      html  css  js  c++  java
  • 19-141. Linked List Cycle

    题目描述:

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

    To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

    Example 1:

    Input: head = [3,2,0,-4], pos = 1
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the second node.
    

    Example 2:

    Input: head = [1,2], pos = 0
    Output: true
    Explanation: There is a cycle in the linked list, where tail connects to the first node.
    

    Example 3:

    Input: head = [1], pos = -1
    Output: false
    Explanation: There is no cycle in the linked list.
    

    Follow up:

    Can you solve it using O(1) (i.e. constant) memory?

    第一种实现方法:

     1 def hasCycle(self, head):
     2     try:
     3         slow = head
     4         fast = head.next
     5         while slow is not fast:
     6             slow = slow.next
     7             fast = fast.next.next
     8         return True
     9     except:
    10         return False

    第二种实现方法:

     1 class Solution(object):
     2     def hasCycle(self, head):
     3         marker1 = head
     4         marker2 = head
     5         while marker2!=None and marker2.next!=None:
     6             marker1 = marker1.next
     7             marker2 = marker2.next.next
     8             if marker2==marker1:
     9                 return True
    10         return False

    分析:这道题可以看做是两个人在一个赛道上赛跑,其中一个人跑的快,另外一个人跑的慢。如果这个赛道有环,那么终究有一天,两个人都会进入环中。而在一个环中,只要两个人的速度不同,那么它们终将相遇。

  • 相关阅读:
    关闭webstorm自动保存,并显示文件未保存标识
    ionic1.3.3 下拉刷新 上拉加载更多
    纯css导航下划线跟随效果【转载】
    wpf获取模板化控件中的动画。
    wpf中dropdownButton控件下拉居中。。。
    C#综合揭秘——深入分析委托与事件
    反射
    多线程,异步
    wcf,socket,数据传输方式
    面向对象五大原则三个基本特征
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/10995640.html
Copyright © 2011-2022 走看看