141. Linked List Cycle

124 阅读1分钟

题目描述

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
xplanation: There is no cycle in the linked list.

解题思路1: 暴力破解

这个题目是判断链表是否存在环. 第一种方法: 我们可以使用哈希表,将遍历过的item存起来, 当我们在哈希表中再次拿到这个item的时候, 就说明已经有环了
空间复杂度: O(n)

示例代码1:

func hasCycle(_ head: ListNode?) -> Bool {
    guard let _ = head else {
        return false
    }
    var hash: [ListNode: Int] = [:]
    var h = head
    while h != nil  {
        if hash[h!] == nil {
            hash[h!] = 1
            h = h?.next
        }else {
            return true
        }
    }   
    return false
}

解题思路2: 快慢指针

我们可以使用快慢指针来做这个题目, 设定2个指针, 快指针每次移动2格, 慢指针每次移动1格, 当2个指针重叠时, 就说明成环了
空间复杂度: O(1)

示例代码2:

func hasCycle(_ head: ListNode?) -> Bool {

    guard let h = head else {
        return false
    }
    // 定义快慢指针
    var slow: ListNode? = h
    var fast: ListNode? = h.next

    while slow != fast  {
        if slow == nil || fast == nil {
            return false
        }else {
            slow = slow?.next   // 慢指针每次移动1格
            fast = fast?.next?.next  // 快指针每次移动2格
        }
    }
    return true
}