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;
    }
}
相关推荐
信奥卷王6 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵6 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG8 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z8 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛9 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记9 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序9 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室9 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
圣保罗的大教堂10 小时前
leetcode 301. 删除无效的括号 困难
leetcode