leetcode 141. Linked List Cycle 常数内存 python3

一.问题描述

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.1 一种是保存每个已访问的元素到集合然后之后对比是否有重复元素,有一个序列重复就说明有环(应该没人用这种方法吧)。

1.2 或者不利用元素值,而是把每个访问元素的节点引用存下来,然后每次到一个节点比较该节点引用之前出现过没用,出现过就说明有环。

主要将第二种方法,就是常数内存法。

2.方法就是设置两个指针,一次移动向后一格,一次向后移动两格(类似追击问题,比如围着一个圈跑步,跑步快的人迟早就在某个时候和跑得慢的再相遇,比如超过一圈),只要链表中存在环,那么肯定在将来某个时刻会存在两个指针所指向的节点内存地址(节点引用)相同,返回。

3.你可以在类定义里多加一个visited属性,遍历一个节点就将visited属性设置为True,和1.2方法差不多。

时间复杂度 1.2:O(N) 1.1 and 2.1 O(2N) 空间复杂度 2.1 O(1) 1.1 and 1.2 O(N)

更多leetcode算法题解法: 专栏 leetcode算法从零到结束  或者 leetcode 解题目录 Python3 一步一步持续更新~

三.源码

1.2:

# version 1
# 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:
        nodeset,flag=set(),False
        while head:
            if head in nodeset:
                flag=True
                break
            else:
                nodeset.add(head)
                head=head.next
        return flag

#version 2
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        nodeset,flag=set(),False
        while not flag and head:
            flag=head in nodeset
            nodeset.add(head)
            head=head.next
        return flag

2.1

# 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:
        if not head:return False
        flag,head2=False,head
        while not flag and head2 and head2.next:
            head2=head2.next.next
            if head==head2:
                flag=True
                break
            head=head.next
        return flag

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值