138. Copy List with Random Pointer

题目:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

链接: http://leetcode.com/problems/copy-list-with-random-pointer/

题解:

刚做过Clone Graph, 一下就想到最简单的DFS Recursive。也是一样用HashMap来保存visited节点,然后进行处理。 看过discuss区后,发现还有很多其他的好解法,要一一试试。 看到一些解法是建立一种A->A'->B->B'->C->C',这样其实也是O(n),不过没有用到HashMap,值得学习借鉴。

Time Complexity - O(n),Space Complexity - O(n)。

public class Solution {
    Map<Integer, RandomListNode> visited = new HashMap<>();
    
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
            return head;
        if(visited.containsKey(head.label))
            return visited.get(head.label);
        RandomListNode root = new RandomListNode(head.label);
        visited.put(root.label, root);
        
        root.next = copyRandomList(head.next);
        root.random = copyRandomList(head.random);
        return root;
    }
}

 

Reference:

https://leetcode.com/discuss/753/is-there-any-faster-method

https://leetcode.com/discuss/12559/my-accepted-java-code-o-n-but-need-to-iterate-the-list-3-times

https://leetcode.com/discuss/14543/no-hashmap-o-n-java-solution

https://leetcode.com/discuss/18049/algorithms-without-extra-array-table-algorithms-explained

https://leetcode.com/discuss/2189/o-n-time-3-passes-o-1-memory-usage-solution

 

转载于:https://www.cnblogs.com/yrbbest/p/4438806.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值