141. 环形链表
xxxixxxx

141. 环形链表

141. 环形链表

快慢指针解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func hasCycle(_ head: ListNode?) -> Bool {
var slowTree = head
var fastTree = head?.next

while slowTree != nil || fastTree != nil {
if slowTree === fastTree {
return true
}
slowTree = slowTree?.next
fastTree = fastTree?.next?.next
}

return false
}

哈希表解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func hasCycle(_ head: ListNode?) -> Bool {
// 注意这里使用 Set, 使用 Array 会超时
// ListNode 需要实现 Equatable, Hashable 协议
var list: Set<ListNode> = []
var head = head

while head != nil {
if list.contains(head!) {
return true
}
list.insert(head!)
head = head?.next
}
return false
}

Swift 链表 及 实现协议

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ListNode {
public var val: Int
public var next: ListNode?
public init() { self.val = 0; self.next = nil }
public init(_ val: Int) { self.val = val; self.next = nil }
public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
}

extension ListNode: Equatable {
public static func == (l: ListNode, r: ListNode) -> Bool {
return l === r
}
}

extension ListNode: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}

  • Post title:141. 环形链表
  • Post author:xxxixxxx
  • Create time:2021-02-21 23:49:00
  • Post link:https://xxxixxx.github.io/2021/02/21/2000-005-141. 环形链表/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments