|
| 1 | +# 001. Two Sum |
| 2 | + |
| 3 | +**<font color=red>难度: Easy</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | +
|
| 9 | +* https://leetcode.com/problems/linked-list-cycle/ |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | +
|
| 13 | +``` |
| 14 | +Given a linked list, determine if it has a cycle in it. |
| 15 | +
|
| 16 | +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. |
| 17 | +``` |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | + |
| 21 | +``` |
| 22 | +Input: head = [3,2,0,-4], pos = 1 |
| 23 | +Output: true |
| 24 | +Explanation: There is a cycle in the linked list, where tail connects to the second node. |
| 25 | +``` |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +**Example 2:** |
| 30 | + |
| 31 | +``` |
| 32 | +Input: head = [1,2], pos = 0 |
| 33 | +Output: true |
| 34 | +Explanation: There is a cycle in the linked list, where tail connects to the first node. |
| 35 | +``` |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +**Example 3:** |
| 40 | + |
| 41 | +``` |
| 42 | +Input: head = [1], pos = -1 |
| 43 | +Output: false |
| 44 | +Explanation: There is no cycle in the linked list. |
| 45 | +``` |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +**Follow up:** |
| 52 | + |
| 53 | +Can you solve it using *O(1)* (i.e. constant) memory? |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +## 解题方案 |
| 58 | + |
| 59 | +> 思路 1 |
| 60 | +******- 时间复杂度: O(N)******- 空间复杂度: O(N)****** |
| 61 | + |
| 62 | +使用`快慢指针`的思路进行解题。就像两个运动员在同一个环形赛道上赛跑,如果一个运动员跑的快,一个跑得慢,最后两个运动员一定会相遇。 |
| 63 | + |
| 64 | +下面代码中的`fast`每次会走两步,而`slow`每次会走一步,如果`fast`没有`next`节点,自然没有环;如果`fast`等于`slow`说明二者相遇,最终为表明存在环。 |
| 65 | + |
| 66 | + |
| 67 | + |
| 68 | +#### 执行结果 |
| 69 | + |
| 70 | +执行用时 :**92 ms**, 在所有 JavaScript 提交中击败了94.16%的用户 |
| 71 | + |
| 72 | +内存消耗 :**36.6 MB**, 在所有 JavaScript 提交中击败了51.93% |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +代码: |
| 77 | + |
| 78 | +```javascript |
| 79 | +/** |
| 80 | + * Definition for singly-linked list. |
| 81 | + * function ListNode(val) { |
| 82 | + * this.val = val; |
| 83 | + * this.next = null; |
| 84 | + * } |
| 85 | + */ |
| 86 | + |
| 87 | +/** |
| 88 | + * @param {ListNode} head |
| 89 | + * @return {boolean} |
| 90 | + */ |
| 91 | +var hasCycle = function(head) { |
| 92 | + if (head === null || head.next === null) { |
| 93 | + return false |
| 94 | + } |
| 95 | + |
| 96 | + let slow = head |
| 97 | + let fast = head.next |
| 98 | + |
| 99 | + while (slow !== fast) { |
| 100 | + if (fast === null || fast.next === null) { |
| 101 | + return false |
| 102 | + } |
| 103 | + slow = slow.next |
| 104 | + fast = fast.next.next |
| 105 | + } |
| 106 | + return true |
| 107 | +}; |
| 108 | +``` |
| 109 | + |
0 commit comments