File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- #https://leetcode.com/problems/linked-list-cycle/
1+ #Two Pointers
2+ #If the linked list has cycle, the fast pointer will eventually catch up.
3+ #time: O(N).
4+ #space: O(1).
25class Solution (object ):
36 def hasCycle (self , head ):
47 fast = head
58 slow = head
69 while fast and fast .next :
710 fast = fast .next .next
811 slow = slow .next
9- if (fast == slow ):
10- return True
11- return False
12+ if fast == slow : return True
13+ return False
14+
15+ #Flag
16+ #Use a flag that stores on the nodes to know if we visited or not.
17+ #time: O(N).
18+ #space: O(N), for each node we use O(1) and there are N nodes.
19+ class Solution (object ):
20+ def hasCycle (self , head ):
21+ curr = head
22+ while curr :
23+ if hasattr (curr , 'visited' ) and curr .visited : return True
24+ curr .visited = True
25+ curr = curr .next
26+ return False
27+
28+ #HashTable
29+ #Use a hash-table to store the visited nodes
30+ #time: O(N).
31+ #space: O(N).
32+ class Solution (object ):
33+ def hasCycle (self , head ):
34+ visited = {}
35+ curr = head
36+ while curr :
37+ if curr in visited : return True
38+ visited [curr ] = None
39+ curr = curr .next
40+ return False
41+
You can’t perform that action at this time.
0 commit comments