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
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103379119