zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    表单的重复提交问题
    js日期操作
    spring data jpa
    Excel Xll开发资料
    Excel DNA学习笔记一
    error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏的解决方案
    点进去勿喷
    hdu1305(字典树)
    2018 Multi-University Training Contest 3
    hihocoder 1014(字典树)
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438806.html
Copyright © 2011-2022 走看看