LeetCode 141. Linked List Cycle

1. Problem Link 🔗

LeetCode 141. Linked List Cycle

2. Solution Overview 🧭

Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer.

Example:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list where the tail connects to the 1st node (0-indexed).

Constraints:

  • The number of nodes in the list is in the range [0, 10^4]
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked-list

Common approaches include:

  • Floyd’s Cycle Detection (Two Pointers): Use slow and fast pointers
  • Hash Set: Store visited nodes in a hash set
  • Marking Nodes: Modify nodes to mark visited ones (destructive)

3. Solution 1: Floyd’s Cycle Detection (Two Pointers) - Recommended

3.1. Algorithm

  • Use two pointers: slow moves one step at a time, fast moves two steps
  • If there’s a cycle, the fast pointer will eventually meet the slow pointer
  • If there’s no cycle, the fast pointer will reach the end (null)

3.2. Important Points

  • O(1) space complexity
  • Most efficient approach
  • Doesn’t modify the original list

3.3. Java Implementation

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head;
        
        while (fast != null && fast.next != null) {
            slow = slow.next;          // Move slow pointer one step
            fast = fast.next.next;     // Move fast pointer two steps
            
            if (slow == fast) {        // Cycle detected
                return true;
            }
        }
        
        return false; // No cycle found
    }
}

3.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

4. Solution 2: Hash Set Approach

4.1. Algorithm思路

  • Traverse the linked list and store each visited node in a hash set
  • If we encounter a node that’s already in the set, there’s a cycle
  • If we reach the end (null), there’s no cycle

4.2. Important Points

  • Simple and intuitive
  • Easy to understand and implement
  • Uses O(n) extra space

4.3. Java Implementation

import java.util.HashSet;

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        HashSet<ListNode> visited = new HashSet<>();
        ListNode current = head;
        
        while (current != null) {
            if (visited.contains(current)) {
                return true; // Cycle detected
            }
            visited.add(current);
            current = current.next;
        }
        
        return false; // No cycle found
    }
}

4.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

5. Solution 3: Node Marking (Destructive)

5.1. Algorithm思路

  • Modify each visited node by setting a special marker (like setting value to a specific number)
  • If we encounter a node that’s already marked, there’s a cycle
  • This approach modifies the original list

5.2. Important Points

  • O(1) space complexity
  • Modifies the original list (not always acceptable)
  • Can cause issues if node values matter

5.3. Java Implementation

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode current = head;
        // Use a special marker value
        int MARKER = Integer.MIN_VALUE;
        
        while (current != null) {
            if (current.val == MARKER) {
                return true; // Cycle detected
            }
            current.val = MARKER; // Mark the node
            current = current.next;
        }
        
        return false; // No cycle found
    }
}

5.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

6. Solution 4: Recursive Approach

6.1. Algorithm思路

  • Use recursion with a hash set to track visited nodes
  • At each step, check if current node has been visited
  • Recursively check the next node

6.2. Important Points

  • Demonstrates recursive thinking
  • Still uses O(n) space for recursion stack and hash set
  • Good for understanding recursion

6.3. Java Implementation

import java.util.HashSet;

public class Solution {
    public boolean hasCycle(ListNode head) {
        return hasCycleHelper(head, new HashSet<>());
    }
    
    private boolean hasCycleHelper(ListNode node, HashSet<ListNode> visited) {
        if (node == null) {
            return false;
        }
        
        if (visited.contains(node)) {
            return true;
        }
        
        visited.add(node);
        return hasCycleHelper(node.next, visited);
    }
}

6.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

7. Solution 5: Optimized Two Pointers with Different Starting Points

7.1. Algorithm思路

  • Variation of Floyd’s algorithm
  • Start slow and fast pointers from different positions
  • Can help avoid some edge cases

7.2. Important Points

  • Slight variation of the classic approach
  • Handles edge cases differently
  • Same time and space complexity

7.3. Java Implementation

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        
        ListNode slow = head;
        ListNode fast = head.next; // Start fast one step ahead
        
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false; // No cycle
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return true; // Cycle detected (slow == fast)
    }
}

7.4. Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)

8. Solution Comparison 📊

SolutionTime ComplexitySpace ComplexityAdvantagesDisadvantages
Floyd’s Cycle DetectionO(n)O(1)Most efficient, no extra spaceMathematical proof needed
Hash SetO(n)O(n)Simple, intuitiveExtra space usage
Node MarkingO(n)O(1)No extra data structuresModifies original list
RecursiveO(n)O(n)Demonstrates recursionStack overflow risk
Optimized Two PointersO(n)O(1)Handles edge cases wellSlightly more complex

9. Summary 📝

  • Key Insight: Floyd’s cycle detection algorithm is the optimal solution for cycle detection in linked lists
  • Recommended Approach: Solution 1 (Floyd’s Cycle Detection) is the industry standard
  • Mathematical Proof: If there’s a cycle, the fast pointer will eventually meet the slow pointer because the fast pointer catches up by 1 node per step
  • Pattern Recognition: This is a fundamental algorithm pattern used in many cycle detection problems

Why Floyd’s Algorithm Works:

  • In each iteration, the distance between fast and slow pointers decreases by 1
  • Once the fast pointer enters the cycle, it will eventually catch up to the slow pointer
  • The time complexity is linear because the fast pointer traverses at most 2n nodes

For interviews, Floyd’s cycle detection algorithm is expected as it demonstrates knowledge of optimal algorithms and space efficiency.

在准备 LeetCode 面试题时,一些高频题目和经典题型是必须掌握的,这些题目覆盖了数组、字符串、链表、树、动态规划等多个方面。以下是一些常见的 LeetCode 面试题: ### 数组与双指针类问题 - **LeetCode 160. Intersection of Two Linked Lists**:判断两个链表是否相交,并找到交点。 - **LeetCode 141. Linked List Cycle**:判断链表中是否存在环。 - **LeetCode 92. Reverse Linked List II**:反转链表的指定部分。 - **LeetCode 328. Odd Even Linked List**:将链表中的奇偶节点分开并连接到一起。 - **LeetCode 面试题 16.06. 最小差**:找到两个数组中差值最小的两个数,常用双指针法解决[^4]。 ### 字符串与哈希类问题 - **LeetCode 242. Valid Anagram**:判断两个字符串是否是变位词,通常使用哈希表或数组统计字符频率来解决[^2]。 - **LeetCode 1. Two Sum**:在数组中找出两个数使其和等于目标值,常用哈希表存储差值。 - **LeetCode 49. Group Anagrams**:将变位词分组,常用于哈希表处理字符串特征。 ### 链表类问题 - **LeetCode 2. Add Two Numbers**:两个链表表示的数字相加,需要考虑进位问题。 - **LeetCode 21. Merge Two Sorted Lists**:合并两个有序链表。 - **LeetCode 234. Palindrome Linked List**:判断链表是否是回文结构,可以使用快慢指针和反转链表结合的方法[^1]。 ### 树与图类问题 - **LeetCode 104. Maximum Depth of Binary Tree**:计算二叉树的最大深度。 - **LeetCode 102. Binary Tree Level Order Traversal**:二叉树的层序遍历。 - **LeetCode 236. Lowest Common Ancestor of a Binary Tree**:找到二叉树的最近公共祖先。 ### 排列组合与回溯类问题 - **LeetCode 面试题 08.08. 有重复字符串的排列组合**:给出有重复字符串的所有排列组合,通常使用回溯法实现[^5]。 - **LeetCode 46. Permutations**:生成不重复数字的所有排列。 - **LeetCode 78. Subsets**:生成一个数组的所有子集。 ### 动态规划类问题 - **LeetCode 70. Climbing Stairs**:爬楼梯问题,动态规划入门题。 - **LeetCode 198. House Robber**:打家劫舍问题,典型的线性动态规划。 - **LeetCode 322. Coin Change**:找零钱的最小硬币数,典型的完全背包问题。 ### 高频经典题 - **LeetCode 3. Longest Substring Without Repeating Characters**:无重复字符的最长子串,滑动窗口法的经典应用[^3]。 - **LeetCode 5. Longest Palindromic Substring**:最长回文子串,扩展中心法或动态规划解决。 - **LeetCode 8. String to Integer (atoi)**:字符串转换为整数,需考虑各种边界条件。 ### 代码示例 以下是一个判断两个字符串是否互为变位词的 Java 示例代码: ```java class Solution { public boolean isAnagram(String s, String t) { if (s.length() != t.length()) return false; int[] num = new int[26]; for (int i = 0; i < s.length(); i++) { num[s.charAt(i) - 'a']++; num[t.charAt(i) - 'a']--; } for (int i : num) { if (i != 0) return false; } return true; } } ``` ### 进阶建议 在准备 LeetCode 面试题时,不仅要掌握这些高频题目,还要理解其背后的数据结构和算法思想,例如快慢指针、双指针、滑动窗口、动态规划等。此外,代码实现要熟练,尤其是链表反转、字符串处理、数组操作等基础操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kuo-Teng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值