·
·
文章目录
  1. 题目介绍
  2. 复杂度
  3. 解题思路

Linked List Cycle

题目介绍

LeetCode 141. Linked List Cycle

复杂度

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

解题思路

算法学习 - 链表 对这题有扩展。

这是一道经典的链表题目 - 环形链表,基本的解题思路是双指针技巧里面的快慢指针。

  • 如果没有环,快指针将停在链表的末尾。
  • 如果有环,快指针最终将与慢指针相遇。

这两个指针的适当速度应该是多少?

一个安全的选择是每次移动慢指针一步,而移动快指针两步。每一次迭代,快速指针将额外移动一步。如果环的长度为 M,经过 M 次迭代后,快指针肯定会多绕环一周,并赶上慢指针。

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
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}

class Solution {
func hasCycle(_ head: ListNode?) -> Bool {
if head == nil || head?.next == nil {
return false
}
var slow = head
var fast = head?.next

while fast?.next != nil && fast?.next?.next != nil {
slow = slow?.next
fast = fast?.next?.next
if slow === fast {
return true
}
}
return false
}
}
**版权声明**

Ivan’s Blog by Ivan Ye is licensed under a Creative Commons BY-NC-ND 4.0 International License.
叶帆创作并维护的叶帆的博客博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证

本文首发于Ivan’s Blog | 叶帆的博客博客( http://yeziahehe.com ),版权所有,侵权必究。

本文链接:http://yeziahehe.com/2020/03/11/LinkedListCycle/

支持一下
扫一扫,支持yeziahehe
  • 微信扫一扫
  • 支付宝扫一扫