环形链表
题目描述:


解题思路:
- 第一种:这个方法思路也很简单,也很容易想到,我们先设了两个指针
Front和Back,都指向链表的头部head,然后开始迭代,Front每次走两步,然后Back每次走一步,这样的话两个指针每次的距离差距都会 +1,如果说链表中存在环,则这两个指针一定会在某个时候相遇,也就是Front == Back,如果Front走完全部链表了都没有相遇,则这个链表中没有环。 - 时间复杂度:O(n) 。
# 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:
Front = head
Back = head
while Front and Back and Front.next:
Front = Front.next.next
Back = Back.next
if Front == Back:
return True
return False

- 第二种:这个方法很厉害,首先是定义了一个
set,然后遍历链表,我们发现每遍历一次就会将head链表中的这个节点的元素放进set中,然后判断每次的节点的元素是不是在这个set中,如果在,则说明有重复元素,也就是说存在环。 - 时间复杂度:O(n)
# 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:
lino = set()
while head:
if head in lino:
return True
lino.add(head)
head = head.next
return False

本文介绍两种高效检测链表中是否存在环的方法:双指针法和哈希集合法。双指针法通过快慢指针移动判断是否相遇,哈希集合法则利用集合存储节点,检查节点是否重复。
1247

被折叠的 条评论
为什么被折叠?



