python linkedlist_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.

34e232f8530c309fbbb5e4121998b0cd.png

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.

5613d64632323b0f0987cc31d360f8fb.png

Example 3:

Input: head = [1], pos = -1

Output: false

Explanation: There is no cycle in the linked list.

0046ffffe7c710782a43cecfad50e5ae.png

思路1:

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

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

代码1:

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

classSolution(object):defhasCycle(self, head):""":type head: ListNode

:rtype: bool"""

if head == None or head.next == None: returnFalse

head2=headwhile head2.next != None and head.next != None:#当两个指针的next都不为None

if (head2.next.next != None):#如果走两步的指针head2的next.next不为None

head2 =head2.next.nextelse:returnFalse

head=head.nextif(head ==head2):returnTruereturn False

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

if not head or not head.next: returnFalse

head2=headwhile not head2 and not head2.next:#只需要关注走的比较快的指针是否为空即可,若较快指针不为空,则较慢指针肯定不为空

head2 =head2.next.next

head=head.nextif(head ==head2):returnTruereturn 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

classSolution(object):defhasCycle(self, head):""":type head: ListNode

:rtype: bool"""

if head == None or head.next == None: returnFalse

head.val= float('inf')while head.next != None:#当指针的next都不为None

if head.val ==head.next.val:returnTrueelse:

head=head.next

head.val= float('inf')return False

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值