LeetCode141. Linked List Cycle

原题地址:https://leetcode.com/problems/linked-list-cycle/description/


题目描述:
Given a linked list, determine if it has a cycle in it.

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


题解:判断一个单项链表是否有环,声明两个指针都指向链表头,然后同时开始遍历。
其中一个指针每次走一步,另一个每次走两步,如果链表存在环,则两个指针迟早会相遇。
此时走的快的指针比走的慢的指针多走了n圈。

假设非环部分长度为a, 换部分长度为b, a+b = n,当慢指针进入环时,循环了a次。假设此时慢指针距离快指针x,即快指针距离慢指针b-x,每次快指针可以缩短1的距离,需要b-x次循环,两者相遇。
a + b - x < a+b = n, 时间复杂度O(n)。


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        a = b = head
        while (a is not None and b is not None):
            a = a.next
            if b.next is not None:
                b = b.next.next
            else:
                return False
            if a == b:
                return True
        return False

16 / 16 test cases passed.
Status: Accepted
Runtime: 63 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值