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

[LeetCode] 138. Copy List with Random Pointer_Medium tag: Linked List

时间:2019-05-04 11:55:30      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:一个   random   pointer   color   over   inter   creat   利用   etc   

这个题目有两种做法,

note: 注意head.random有可能是None的情况

1. S: O(n)    create一个dictionary,然后先建dictionary和copy list以及next指针。然后再一遍,去建random指针。

2: S: O(1)    利用如下图所示的结构,然后再将copy node和原来的node分开即可。

Old List: A --> B --> C --> D
InterWeaved List: A --> A‘ --> B --> B‘ --> C --> C‘ --> D --> D‘

1. code S:O(n)
class Node:
    def __init__(self, x, next, random):
        self.val = x
        self.next = next
        self.random = random

class Solution:
    def deepCopyList(self, head):
        dummy, listMap = Node(0, None, None), dict()
        head1, head2 = head, dummy
        # copy the list and next pointers
        while head1:
            head2.next = Node(head1.val, None, None)
            ListMap[head1] = head2.next
            head1 = head1.next
            head2 = head2.next
        # copy the random pointers
        head1, head2 = head, dummy.next
        while head1:
            if head1.random: # head1.random can be None
                head2.random = listMap[head1.random]
            head1 = head1.next
            head2 = head2.next
        return dummy.next

 

2. code     S: O(1)

def deepCopyList(self, head):
    dummy = Node(0, None, None)
    dummy.next = head
    # make copy nodes
    while head:
        temp = head.next
        head.next = Node(head.val, None, None)
        head.next.next = temp
        head = temp
    # create random pointers
    head = dummy.next
    while head:
        if head.random:
            head.next.random = head.random.next
        head = head.next.next
    # make copy list and recover the original list
    dummy2 = Node(0, None, None)
    head1, head2 = dummy.next, dummy2
    while head1:
        head2.next = head1.next
        head1.next= head1.next.next
        head1 = head1.next
        head2 = head2.next
    return dummy2.next

 

[LeetCode] 138. Copy List with Random Pointer_Medium tag: Linked List

标签:一个   random   pointer   color   over   inter   creat   利用   etc   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10807771.html

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