美文网首页
141.环形链表

141.环形链表

作者: faterman | 来源:发表于2021-04-16 10:58 被阅读0次

一、哈希表

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 {
        //方法1. 一次遍历,使用HashMap的方法存储这个点之前出现过没有
        //时间复杂度O(N),控件复杂度O(1)
        //边界条件
        guard var head = head else {
            return false
        }
        var haveSeen = Set<ListNode>()
        while head.next != nil {
            if !haveSeen.add(head) {
                return true
            }
            head = head.next!
        }
        return false
    }
}

二、快慢指针

class Solution {
    func hasCycle(_ head: ListNode?) -> Bool {
        var slowNode = head
        var fastNode = head?.next
        while fastNode?.next != nil {
            if slowNode === fastNode {
                return true
            }
            slowNode = slowNode?.next
            fastNode = fastNode?.next?.next
        }
        
        return false
    }
}

相关文章

网友评论

      本文标题:141.环形链表

      本文链接:https://www.haomeiwen.com/subject/dwzslltx.html