LeetCode 刷题【138. 随机链表的复制】

138. 随机链表的复制

自己做

解:哈希表

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 {
    public Node copyRandomList(Node head) {
        Node p = head;
        Node res = new Node(0);
        Node q = res;
        List<Node> list = new ArrayList();
        Map<Node, Integer> hash1 = new HashMap();
        int i = 0;

        //根据next复制链表
        while(p != null){
            q.next = new Node(p.val);
            q = q.next;

            hash1.put(p, i);
            list.add(q);
            
            p = p.next;
            i++;
        }

        //建立random
        p = head;
        q = res.next;

        while(p != null){
            if(p.random != null)
                q.random = list.get(hash1.get(p.random));
            else
                q.random = null;

            p = p.next;
            q = q.next;
        }


        return res.next;
    }
}
相关推荐
却道天凉_好个秋4 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与5 小时前
算法24.0
算法
晓北斗NorSnow5 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习
hans汉斯6 小时前
【计算机科学与应用】基于BERT与DeepSeek大模型的智能舆论监控系统设计
大数据·人工智能·深度学习·算法·自然语言处理·bert·去噪
多喝开水少熬夜7 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm
立志成为大牛的小牛8 小时前
数据结构——三十七、关键路径(王道408)
数据结构·笔记·程序人生·考研·算法
ytttr8738 小时前
基于MATLAB的Relief算法特征权重选择实现
算法
Freshman小白9 小时前
python算法打包为docker镜像(边缘端api服务)
python·算法·docker
mit6.8249 小时前
[VT-Refine] Simulation | Fine-Tuning | docker/run.sh
算法