Skip to content

Commit 9b00e00

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent 0831e25 commit 9b00e00

File tree

2 files changed

+19
-19
lines changed

2 files changed

+19
-19
lines changed

problems/linked-list-cycle-ii.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
#Flag
2+
#Use a flag that stores on the nodes to know if we visited or not.
3+
#time: O(N).
4+
#space: O(N), for each node we use O(1) and there are N nodes.
15
class Solution(object):
26
def detectCycle(self, head):
37
curr = head
@@ -7,12 +11,16 @@ def detectCycle(self, head):
711
curr = curr.next
812
return None
913

14+
#HashSet
15+
#Use a hash-set to store the visited nodes
16+
#time: O(N).
17+
#space: O(N).
1018
class Solution(object):
1119
def detectCycle(self, head):
1220
visited = set()
1321
curr = head
1422
while curr:
15-
if curr in visited: return True
23+
if curr in visited: return curr
1624
visited.add(curr)
1725
curr = curr.next
18-
return False
26+
return None

problems/merge-two-sorted-lists.py

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,20 @@
11
#https://leetcode.com/problems/merge-two-sorted-lists/
2+
23
class Solution(object):
34
def mergeTwoLists(self, l1, l2):
4-
if l1==None and l2==None:
5-
return None
6-
elif l1 and l2==None:
7-
return l1
8-
elif l1==None and l2:
9-
return l2
10-
11-
pre = ListNode
12-
curr = pre
5+
pre_head = ListNode(-1)
6+
curr = pre_head
137

148
while l1 and l2:
15-
if l1.val<=l2.val:
9+
if l1.val<l2.val:
1610
curr.next = l1
1711
l1 = l1.next
1812
else:
1913
curr.next = l2
2014
l2 = l2.next
2115
curr = curr.next
22-
23-
if l1:
24-
curr.next = l1
25-
elif l2:
26-
curr.next = l2
27-
28-
return pre.next
16+
17+
if l1: curr.next = l1
18+
if l2: curr.next = l2
19+
20+
return pre_head.next

0 commit comments

Comments
 (0)