Python3解leetcode 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 poswhich 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.

思路1:

设置两个指针,一个每次走一步,一个每次走两步,那么如果有环,两个指针一定会相遇。

但这个代码写出来仅仅beats 28.6%,效率不高

代码1:

# 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
        """
        if head == None or head.next == None: return False
        head2 = head
        while head2.next != None and head.next != None:#当两个指针的next都不为None
            if (head2.next.next != None):#如果走两步的指针head2的next.next不为None
                head2 = head2.next.next
            else:
                return False
            head = head.next
            if(head == head2):
                return True
        return False

将上述思路优化后,代码如下:

if not head  or not head.next: return False
        head2 = head
        while not head2 and not head2.next:#只需要关注走的比较快的指针是否为空即可,若较快指针不为空,则较慢指针肯定不为空
            head2 = head2.next.next
            head = head.next
            if(head == head2):
                return True
        return False  

思路2:

循环遍历整个列表,将遍历过的节点值设置为inf(最大值),如果后续遍历的节点值有等于inf的,则证明有环,否则就是没有环。

该算法写出来beats65.7%的人,还需要优化

代码2:

# 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
        """
        if head == None or head.next == None: return False
        head.val = float(‘inf‘)
        while head.next != None:#当指针的next都不为None
            if head.val == head.next.val:
                return True
            else:
                head = head.next
                head.val = float(‘inf‘)
        return False

原文地址:https://www.cnblogs.com/xiaohua92/p/11080739.html

时间: 2024-08-30 16:04:34

Python3解leetcode Linked List Cycle的相关文章

LeetCode Linked List Cycle II

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode* fast = head; ListNode* slow = head;

LeetCode: Linked List Cycle [141]

[题目] Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? [题意] 判断一个单向链表是否有环 [思路] 维护两个指针p1和p2,p1每次向前移动一步,p2每次向前移动两步 如果p2能够追上p1,则说明链表中存在环 [代码] /** * Definition for singly-linked list. * struct L

LeetCode: Linked List Cycle II [142]

[题目] Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? [题意] 给定一个单向链表,如果链表有环,则返回环开始的位置. [思路] 仍然是维护两个指针, p1, p2, p1每次走一步, p2每次走两步 假设进入环之前要走X步,环长为y步,p2第

leetcode --- Linked List Cycle [Floyd's cycle-finding algorithm]

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? Linked List Two Pointers ''' Created on Nov 13, 2014 @author: ScottGu<[email protected], [email protected]> ''' # Definit

Leetcode:Linked List Cycle 链表是否存在环

Linked List Cycle: Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using extra space? 解题分析: 大致思想就是设置两个指针,一个指针每次走两步,一个指针每次走一步,如果这两个指针碰头了,那么一定就存在环 可以类比两个人在环形操场跑步,同时出发,一个跑得快,一个跑得慢,如果跑得快的人追上跑得慢的人,那么跑得快的人相当于多跑了一整

[LeetCode]Linked List Cycle II解法学习

问题描述如下: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? 从问题来看,如果可以充分利用额外空间的话,这个题目是不难的,然而题目提出了一个要求,能否在不使用任何额外空间的情况下解决这个问题. 通过反复思考,我觉得这题类似于追击问题,可以用一个

[LeetCode]Linked List Cycle

题目:Linked List Cycle 判断一个单链表中是否有环,要求常量空间复杂度: 思路: 使用两个指针同时从链表表头开始移动,一个移动一步,一个移动两步,直到两个指针重合或某一指针指向链尾. 两个指针重合则单链表有环存在,否则没有. 第二个指针以第一个指针的两倍的速度移动,而第一个指针每次移动一步,这样只要有环,两个指针必定能重合. bool LeetCode::hasCycle(ListNode *head){ if (!head)return false; ListNode *p =

[Leetcode] Linked list cycle ii 判断链表是否有环

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Follow up:Can you solve it without using extra space? 题意:给定链表,若是有环,则返回环开始的节点,没有则返回NULL 思路:题目分两步走,第一.判断是否有环,第二若是有,找到环的起始点.关于第一点,可以参考之前的博客 Linked list cycle.

LeetCode: Linked List Cycle ii 解题报告

Linked List Cycle ii Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? SOLUTION 1: 最开始的想法和 Linked List Cycle这一题一样. SOLUTION 2: 同样是两个指针,一快一慢,相遇时跳出循环,只