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

  • 相关阅读:
    webpack—从零开始配置
    多媒体标签 API(video、audio)
    node 爬虫
    node 操作数据库
    es6+
    UI 组件库 引入使用的问题
    单页应用存在 的问题
    ajax 封装(集中 认证、错误、请求loading处理)
    moment.js 时间库
    文件上传大小被限制的解决方案。
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4438806.html
Copyright © 2011-2022 走看看