leetcode 142. Linked List Cycle II

题目描述

哈希表解法

这个方法很容易想到,但需要O(N)的空间。

cpp 复制代码
/**
 * 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) {
        unordered_set<ListNode*> hash_table;
        ListNode* cur = head;
        while(cur){
            if(hash_table.contains(cur))
                return cur;
            hash_table.insert(cur);
            cur = cur->next;
        }
        return nullptr;
    }
};

双指针法

判断是否有环只需要快慢指针就可以。要确定环的位置,还需要考虑数量关系。具体推导见LeetCode官方题解。

cpp 复制代码
/**
 * 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) {
        if(head == nullptr || head->next == nullptr)
            return nullptr;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next && fast->next->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow){
                ListNode* p1 = fast;
                ListNode* p2 = head;
                while(p1!=p2){
                    p1 = p1->next;
                    p2 = p2->next;
                }
                return p1;
            }
        }
        return nullptr;
    }
};
相关推荐
We་ct10 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
一条大祥脚10 小时前
ABC357 基环树dp|懒标记线段树
数据结构·算法·图论
tod11310 小时前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
苦藤新鸡10 小时前
50.腐烂的橘子
数据结构·算法
无限进步_10 小时前
面试题 02.02. 返回倒数第 k 个节点 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio
Hello World . .11 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·vim
Yvonne爱编码11 小时前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
iAkuya11 小时前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
近津薪荼12 小时前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
松☆12 小时前
Dart 中的常用数据类型详解(含 String、数字类型、List、Map 与 dynamic) ------(2)
数据结构·list