Skip to content

Commit 0831e25

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent 54afc6a commit 0831e25

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

problems/linked-list-cycle-ii.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution(object):
2+
def detectCycle(self, head):
3+
curr = head
4+
while curr:
5+
if hasattr(curr, 'visited') and curr.visited: return curr
6+
curr.visited = True
7+
curr = curr.next
8+
return None
9+
10+
class Solution(object):
11+
def detectCycle(self, head):
12+
visited = set()
13+
curr = head
14+
while curr:
15+
if curr in visited: return True
16+
visited.add(curr)
17+
curr = curr.next
18+
return False

problems/linked-list-cycle.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def hasCycle(self, head):
99
while fast and fast.next:
1010
fast = fast.next.next
1111
slow = slow.next
12-
if fast==slow: return True
12+
if fast is slow: return True
1313
return False
1414

1515
#Flag
@@ -25,17 +25,17 @@ def hasCycle(self, head):
2525
curr = curr.next
2626
return False
2727

28-
#HashTable
29-
#Use a hash-table to store the visited nodes
28+
#HashSet
29+
#Use a hash-set to store the visited nodes
3030
#time: O(N).
3131
#space: O(N).
3232
class Solution(object):
3333
def hasCycle(self, head):
34-
visited = {}
34+
visited = set()
3535
curr = head
3636
while curr:
3737
if curr in visited: return True
38-
visited[curr] = None
38+
visited.add(curr)
3939
curr = curr.next
4040
return False
4141

0 commit comments

Comments
 (0)