美文网首页
141. 环形链表

141. 环形链表

作者: 浅浅星空 | 来源:发表于2020-02-19 10:58 被阅读0次
  1. 环形链表
image.png

方法一:哈希表

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;
}

时间复杂度:O(1)
空间复杂度:O(n)

方法二:双指针

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;
}

时间复杂度:O(n) 记得分两种情况考虑:有环和无环
空间复杂度:O(1)


image.png

相关文章

网友评论

      本文标题:141. 环形链表

      本文链接:https://www.haomeiwen.com/subject/nwlnfhtx.html