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;
    }
}
相关推荐
一招定胜负2 分钟前
决策树开篇
算法·决策树·机器学习
GoWjw3 分钟前
C语言高级特性
c语言·开发语言·算法
carver w6 分钟前
说人话版 K-means 解析
算法·机器学习·kmeans
小O的算法实验室12 分钟前
2026年SEVC SCI2区,基于差分向量内学习策略的自适应指数交叉差分进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
gloomyfish20 分钟前
【最新技术】多模态零样本工业缺陷检测概述
人工智能·算法·计算机视觉
渡过晚枫22 分钟前
[蓝桥杯/java/算法]攻击次数
java·算法·蓝桥杯
风筝在晴天搁浅23 分钟前
hot100 3.无重复字符的最长子串
数据结构·算法·leetcode
liuyao_xianhui26 分钟前
寻找旋转排序数组中的最小值_优选算法(二分算法)
算法
努力学算法的蒟蒻30 分钟前
day37(12.18)——leetcode面试经典150
算法·leetcode·面试
超级种码38 分钟前
All In AI——DSPy框架,让智能体开发像模型训练一样
大数据·人工智能·算法