0141._Linked_List_Cycle

0141. Linked List Cycle

难度: Easy

刷题内容

原题连接

内容描述

1
2
3
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:

1
2
3
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.

img

Example 2:

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

img

Example 3:

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

img

Follow up:

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

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

使用快慢指针的思路进行解题。就像两个运动员在同一个环形赛道上赛跑,如果一个运动员跑的快,一个跑得慢,最后两个运动员一定会相遇。

下面代码中的fast每次会走两步,而slow每次会走一步,如果fast没有next节点,自然没有环;如果fast等于slow说明二者相遇,最终为表明存在环。

执行结果

执行用时 :92 ms, 在所有 JavaScript 提交中击败了94.16%的用户

内存消耗 :36.6 MB, 在所有 JavaScript 提交中击败了51.93%

代码:

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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/

/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (head === null || head.next === null) {
return false
}

let slow = head
let fast = head.next

while (slow !== fast) {
if (fast === null || fast.next === null) {
return false
}
slow = slow.next
fast = fast.next.next
}
return true
};