File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * public var val: Int
5
+ * public var next: ListNode?
6
+ * public init(_ val: Int) {
7
+ * self.val = val
8
+ * self.next = nil
9
+ * }
10
+ * }
11
+ */
12
+
13
+ extension ListNode : Equatable {
14
+ public static func == ( lhs: ListNode , rhs: ListNode ) -> Bool {
15
+ return lhs === rhs
16
+ }
17
+ }
18
+
19
+ extension ListNode : Hashable {
20
+ public func hash( into hasher: inout Hasher ) {
21
+ hasher. combine ( ObjectIdentifier ( self ) )
22
+ }
23
+ }
24
+
25
+ class Solution {
26
+ // O(n) time / O(n) space
27
+ func hasCycle( _ head: ListNode ? ) -> Bool {
28
+ var visitedNodes = Set < ListNode > ( )
29
+ var node = head
30
+
31
+ while node != nil {
32
+ guard let currentNode = node else {
33
+ return false
34
+ }
35
+
36
+ if visitedNodes. contains ( currentNode) {
37
+ return true
38
+ }
39
+
40
+ visitedNodes. insert ( currentNode)
41
+ node = currentNode. next
42
+ }
43
+
44
+ return false
45
+ }
46
+
47
+ // O(n) time / O(1) space
48
+ func hasCycleFloyd( _ head: ListNode ? ) -> Bool {
49
+ var slow = head
50
+ var fast = head
51
+
52
+ while fast != nil && fast? . next != nil {
53
+ slow = slow? . next
54
+ fast = fast? . next? . next
55
+
56
+ if slow === fast {
57
+ return true
58
+ }
59
+ }
60
+
61
+ return false
62
+ }
63
+ }
You can’t perform that action at this time.
0 commit comments