每日一道LeetCode——环形链表

题目

在这里插入图片描述
在这里插入图片描述

解法一:哈希表

附:HashSet和HashMap的区别
在这里插入图片描述

public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}

在这里插入图片描述
(这种方法比较容易想到,重点看官方的双指针解法,关于时间复杂度的优化)

解法二:双指针

在这里插入图片描述

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) {
        return false;
    }
    ListNode slow = head;
    ListNode fast = head.next;
    while (slow != fast) {
        if (fast == null || fast.next == null) {
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
}

在这里插入图片描述


版权声明:本文为weixin_41945051原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。