Skip to content

Commit 6ef0afe

Browse files
author
Chris Wu
committed
no message
1 parent 8c11b0d commit 6ef0afe

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

problems/clone-graph.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,28 @@ def cloneGraph(self, start):
5454

5555
return clone[start]
5656

57-
58-
57+
#2020/8/7, similar to 2
58+
class Solution(object):
59+
def cloneGraph(self, node):
60+
if not node: return node
61+
62+
visited = set()
63+
clones = {}
64+
stack = []
65+
66+
stack.append(node)
67+
while stack:
68+
curr = stack.pop()
69+
if curr in visited: continue
70+
visited.add(curr)
71+
clones[curr] = Node(curr.val)
72+
stack.extend(curr.neighbors)
73+
74+
for curr in clones:
75+
clones[curr].neighbors = [clones[c] for c in curr.neighbors]
76+
77+
return clones[node]
78+
5979

6080

6181

problems/copy-list-with-random-pointer.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,29 @@ def copyRandomList(self, head):
3131
curr = curr.next
3232
curr_copy = curr_copy.next
3333

34-
return head_copy
34+
return head_copy
35+
36+
# 2020/8/11
37+
class Solution(object):
38+
def copyRandomList(self, head):
39+
if not head: return head
40+
41+
clones = {}
42+
43+
curr = head
44+
while curr:
45+
clones[curr] = Node(curr.val)
46+
curr = curr.next
47+
48+
curr = head
49+
while curr:
50+
if curr.next: clones[curr].next = clones[curr.next]
51+
if curr.random: clones[curr].random = clones[curr.random]
52+
curr = curr.next
53+
54+
return clones[head]
55+
56+
"""
57+
Time: O(N). Two iteration. First iteration make a the clones. Second iteration setup the links.
58+
Space: O(1). No extra space except the cloned node.
59+
"""

0 commit comments

Comments
 (0)