100天精刷LeetCode-Day5:141 Linked List Cycle问题(附详细思路和python题解)

题目描述

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.

思路

  • 解法一:如果有cycle,那么可以构造一个快指针一个慢指针,早晚会快指针会绕着环追上慢指针。所以当快指针==慢指针的时候就return True
  • 解法二:也可以用HashTable的方法去解决,每一个没见过的Node都存到一个set里面,如果head.next是set内的元素,那么就return True,反之一直到head.next==None还没有重复那么就没有环。

代码

解法一:

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

class Solution:
    def hasCycle(self, head: ListNode) -> bool:

        fast, slow = ListNode(0), ListNode(0)
        fast.next = head
        slow.next = head
        while fast:
            if not fast.next: return False
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return True

解法二:

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

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        visited = set()
        dummy = ListNode(0)
        dummy.next = head
        while head:
            if not head in visited:
                visited.add(head)
                head=head.next
            else:
                return True
        return False
        

分析

解法一:

  • 时间复杂度 O ( n ) O(n) O(n)
  • 空间复杂度 O ( 1 ) O(1) O(1)

解法二:

  • 时间复杂度 O ( n ) O(n) O(n)
  • 空间复杂度 O ( n ) O(n) O(n)

思考

这道题是第一次碰到快慢指针的题目。它相对的优势就是能在 O ( 1 ) O(1) O(1)的空间复杂度下解决问题。
快慢指针对于链表问题有很多特殊的快速解法:

  1. 使用快慢指针来找到链表的中点234.Palindrome Linked List
  2. 链表的翻转143. Reorder List
  3. 链表的环问题(即本体)以及环的入口142 Linked List Cycle

接下来几天我将把这几题详细地写出题解形成个链表的小专题。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值