力扣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);
    }
}
相关推荐
生成论实验室13 分钟前
《事件关系阴阳博弈动力学:识势应势之道》第十一篇:双脑协同——WOLM与大模型的共生智能
人工智能·算法·语言模型·架构·创业创新
上弦月-编程31 分钟前
高效编程利器:转移表技术解析
c语言·开发语言·数据结构·算法·排序算法
薇茗31 分钟前
【初阶数据结构】 左右逢源的分支诗律 二叉树2
c语言·数据结构·算法·二叉树
AZaLEan__34 分钟前
算法考核题解
算法
MediaTea1 小时前
AI 术语通俗词典:ID3 算法
人工智能·算法
Morwit1 小时前
【力扣hot100】 221. 最大正方形
前端·算法·leetcode
呃呃本1 小时前
算法题(矩阵)
线性代数·算法·矩阵
呃呃本1 小时前
算法题(普通数组、矩阵)
线性代数·算法·矩阵
计算机安禾1 小时前
【计算机网络】第11篇:链路状态路由协议——Dijkstra算法与OSPF的分区架构
计算机网络·算法·架构
珂朵莉MM1 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第二赛季优化题--遗传算法
人工智能·算法