码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-138-复制带随机指针的链表

时间:2019-07-16 20:08:56      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:while   dom   efi   style   val   info   ext   solution   ini   

题目描述:

技术图片

 

方法一:回溯 O(N) O(N)

"""
# Definition for a Node.
class Node:
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution:
    def __init__(self):
        self.dic = {}
    def copyRandomList(self, head: Node) -> Node:
        if not head:
            return None
        elif head in self.dic:
            return self.dic[head]
        node_ = Node(head.val,None,None)
        self.dic[head] = node_
        node_.next = self.copyRandomList(head.next)
        node_.random = self.copyRandomList(head.random)
        
        return self.dic[head]#node

 方法二:迭代 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

 

leetcode-138-复制带随机指针的链表

标签:while   dom   efi   style   val   info   ext   solution   ini   

原文地址:https://www.cnblogs.com/oldby/p/11197086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!