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.
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.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
0141. Linked List Cycle
难度: Easy
刷题内容
Example 1:
Example 2:
Example 3:
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
解题方案
使用
快慢指针
的思路进行解题。就像两个运动员在同一个环形赛道上赛跑,如果一个运动员跑的快,一个跑得慢,最后两个运动员一定会相遇。下面代码中的
fast
每次会走两步,而slow
每次会走一步,如果fast
没有next
节点,自然没有环;如果fast
等于slow
说明二者相遇,最终为表明存在环。执行结果
执行用时 :92 ms, 在所有 JavaScript 提交中击败了94.16%的用户
内存消耗 :36.6 MB, 在所有 JavaScript 提交中击败了51.93%
代码: