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.

    M1: extra space, 用hash map

    用hashmap遍历一遍list,存下每个节点,key是当前node,value存复制的node,map.put(cur, new RandomListNode(cur.label))。再遍历一遍,copy list,除了next,random指针也要复制

    time: O(n), space: O(n)

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head == null) {
                return head;
            }
            HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
            RandomListNode cur = head;
            while(cur != null) {
                map.put(cur, new RandomListNode(cur.label));
                cur = cur.next;
            }
            cur = head;
            while(cur != null) {
                map.get(cur).next = map.get(cur.next);
                map.get(cur).random = map.get(cur.random);
                cur = cur.next;
            }
            return map.get(head);
        }
    }

    M2: 不用extra space, interweave structure

    time: O(n), space: O(1)

  • 相关阅读:
    当模型验证未通过时,获取未通过验证的属性
    在ASP.Net MVC中进行身份认证
    c#生成验证码
    HTTP与FTP状态码
    VUEX
    JS模块化
    Vue.JS入门下
    flex布局
    asp.net Web API
    JWT加密解密
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10179825.html
Copyright © 2011-2022 走看看