友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

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

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
0141 01

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
0141 03

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

思路分析

除了双指针外,还可以使用 Map 来解决。只是空间复杂度要高一些。

0141 04
0141 05
0141 06
0141 07
0141 08
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
 *
 * Memory Usage: 37.9 MB, less than 84.29% of Java online submissions for Linked List Cycle.
 */
public boolean hasCycle(ListNode head) {
    if (Objects.isNull(head)) {
        return false;
    }
    ListNode slow = head;
    ListNode fast = head.next;
    while (Objects.nonNull(fast)) {
        if (slow == fast) {
            return true;
        }
        slow = slow.next;
        fast = fast.next;
        if (Objects.nonNull(fast)) {
            fast = fast.next;
        }
    }
    return false;
}

/**
 * Runtime: 5 ms, faster than 6.60% of Java online submissions for Linked List Cycle.
 *
 * Memory Usage: 38.3 MB, less than 82.14% of Java online submissions for Linked List Cycle.
 *
 * Copy from: https://leetcode.com/problems/linked-list-cycle/solution/[Linked List Cycle solution - LeetCode]
 */
public boolean hasCycleMap(ListNode head) {
    Set<ListNode> nodes = new HashSet<>();
    ListNode current = head;
    while (Objects.nonNull(current)) {
        if (nodes.contains(current)) {
            return true;
        } else {
            nodes.add(current);
        }
        current = current.next;
    }
    return false;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
 * 快慢指针
 */
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;
    fast = fast.next.next;
    if (slow == fast) {
      return true;
    }
  }
  return false;
}