leetcode-138-复制带随机指针的链表
题目描述:
方法一:dfs O(N) O(N)
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
def dfs(head):
if not head:
return None
if head in visited:
return visited[head]
copy = Node(head.val,None,None)
visited[head] = copy
copy.next = dfs(head.next)
copy.random = dfs(head.random)
return copy
visited = {}
return dfs(head)
方法二:迭代 O(n) O(N)
class Solution: def __init__(self): self.visited = {} def getClonedNode(self,node): if node: if node in self.visited: return self.visited[node] else: self.visited[node] = Node(node.val, None, None) return self.visited[node] return None def copyRandomList(self, head: 'Node') -> 'Node': if not head: return head old_node = head new_node = Node(old_node.val, None, None) self.visited[old_node] = new_node while old_node != None: new_node.random = self.getClonedNode(old_node.random) new_node.next = self.getClonedNode(old_node.next) old_node = old_node.next new_node = new_node.next return self.visited[head]
方法三:迭代O(n)O(1)
""" # Definition for a Node. class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': if not head: return head ptr = head while ptr: new_node = Node(ptr.val, None, None) new_node.next = ptr.next ptr.next = new_node ptr = new_node.next ptr = head while ptr: ptr.next.random = ptr.random.next if ptr.random else None ptr = ptr.next.next ptr_old_list = head # A->B->C ptr_new_list = head.next # A'->B'->C' head_old = head.next while ptr_old_list: ptr_old_list.next = ptr_old_list.next.next ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None ptr_old_list = ptr_old_list.next ptr_new_list = ptr_new_list.next return head_old
方法四:dfs
class Solution: def copyRandomList(self, head: 'Node') -> 'Node': visited = {} def bfs(head): if not head: return head clone = Node(head.val,None,None) queue = [head] visited[head] = clone while queue: tmp = queue.pop(0) if tmp.next and tmp.next not in visited: visited[tmp.next] = Node(tmp.next.val) queue.append(tmp.next) if tmp.random and tmp.random not in visited: visited[tmp.random] = Node(tmp.random.val) queue.append(tmp.random) visited[tmp].next = visited.get(tmp.next) visited[tmp].random = visited.get(tmp.random) return clone return bfs(head)