力扣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);
    }
}
相关推荐
Christo310 分钟前
TFS-1996《The Possibilistic C-Means Algorithm: Insights and Recommendations》
人工智能·算法·机器学习
地平线开发者3 小时前
理想汽车智驾方案介绍专题 3 MoE+Sparse Attention 高效结构解析
人工智能·算法·自动驾驶
pusue_the_sun3 小时前
C语言强化训练(1)
c语言·开发语言·算法
一支鱼7 小时前
leetcode-2-两数相加
算法·leetcode·typescript
斯坦索尼8 小时前
关于 01 背包问题的简单解释,理解状态转移与继承的相似性
算法·01背包问题
学涯乐码堂主8 小时前
《信息学奥林匹克辞典》中的一个谬误
数据结构·c++·算法·青少年编程·排序算法·信奥·gesp 考试
一匹电信狗9 小时前
【C++】C++11新特性第一弹(列表初始化、新式声明、范围for和STL中的变化)
服务器·开发语言·c++·leetcode·小程序·stl·visual studio
我叫黑大帅10 小时前
从奶奶挑菜开始:手把手教你搞懂“TF-IDF”
人工智能·python·算法
傻豪10 小时前
【Hot100】贪心算法
算法·贪心算法
黑色的山岗在沉睡11 小时前
LeetCode 3665. 统计镜子反射路径数目
算法·leetcode·职场和发展