LeetCode - 解题笔记 - 141 - Linked List Cycle

Solution 1

判断链表中有环,最直接的方案就是使用哈希表检查是否遍历过。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的长度,线性遍历一次
  • 空间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的长度,哈希表占用,每个节点一个空间
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == nullptr) {
            return false;
        }
        
        unordered_set<ListNode*> checked;
        while (head != nullptr) {
            if (checked.find(head) != checked.end()) {
                return true;
            }
            checked.insert(head);
            head = head->next;
        }
        
        return false;
    }
};

Solution 2

【参考官方】参考官方题解环形链表 - 环形链表 - 力扣(LeetCode) (leetcode-cn.com) 中的Floyd 判圈算法。使用快慢指针在链表上遍历,如果存在环,那么总有一个时间快指针会从后面(正向遍历过程)追上满指针。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入链表的长度,线性遍历,存在环的情况下至多遍历 2 N 2N 2N
  • 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == nullptr || head->next == nullptr) {
            return false;
        }
        
        auto slow = head;
        auto fast = head->next;
        // 利用快慢指针是否相遇确定是否存在环
        while (slow != fast) {
            if (fast == nullptr || fast->next == nullptr) {
                return false;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        
        return true;
    }
};

Solution 3

Solution 1的Python实现

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

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if head is None:
            return False
        
        checked = set()
        while head is not None:
            if head in checked:
                return True
            
            checked.add(head)
            head = head.next
        
        
        return False

Solution 4

Solution 2的Python实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值