力扣138. 随机链表的复制

Problem: 138. 随机链表的复制

文章目录

题目描述

思路及解法

1.创建Map集合Map<Node, Node> map;创建指针cur指向head;

2.遍历链表将cur作为键,new Node(cur.val)作为值,存入map集合;

3.再次遍历链表,利用map集合存贮的键,将创建的节点(map集合中的值)连接起来,最后返回新链表的头节点

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为链表的大小

空间复杂度:

O ( n ) O(n) O(n)

Code

java 复制代码
/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

class Solution {
    /**
     * Copy List with Random Pointer
     *
     * @param head The head of linked list
     * @return Node
     */
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        Map<Node, Node> map = new HashMap<>();
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            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);
    }
}
相关推荐
Dfreedom.几秒前
机器学习经典算法全景解析与演进脉络(监督学习篇)
人工智能·学习·算法·机器学习·监督学习
Zaly.1 分钟前
【Python刷题】LeetCode 3567 子矩阵的最小绝对差
python·leetcode·矩阵
2301_807367198 分钟前
C++代码风格检查工具
开发语言·c++·算法
Morwit9 分钟前
*【力扣hot100】 215. 数组中的第K个最大元素
数据结构·c++·算法·leetcode·职场和发展
奔袭的算法工程师9 分钟前
用AI写天线阵列排布算法
人工智能·算法·信号处理
ab15151710 分钟前
3.20二刷基础121、127,完成进阶61、62
数据结构·算法·排序算法
I_LPL11 分钟前
day58 代码随想录算法训练营 图论专题11
数据结构·算法·图论
m0_7301151116 分钟前
C++中的命令模式实战
开发语言·c++·算法
小比特_蓝光19 分钟前
算法篇1-----双指针
数据结构·算法
我是咸鱼不闲呀23 分钟前
力扣Hot100系列21(Java)——[多维动态规划]总结(不同路径,最小路径和,最长回文子串,最长公共子序列, 编辑距离)
java·leetcode·动态规划