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 分钟前
hot100 78.子集
java·算法
Jasmine_llq7 分钟前
《P4587 [FJOI2016] 神秘数》
算法·倍增思想·稀疏表(st 表)·前缀和数组(解决静态区间和查询·st表核心实现高效预处理和查询·预处理优化(提前计算所需信息·快速io提升大规模数据读写效率
超级大只老咪21 分钟前
快速进制转换
笔记·算法
m0_7066532343 分钟前
C++编译期数组操作
开发语言·c++·算法
故事和你911 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
qq_423233901 小时前
C++与Python混合编程实战
开发语言·c++·算法
TracyCoder1231 小时前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
m0_715575341 小时前
分布式任务调度系统
开发语言·c++·算法
naruto_lnq2 小时前
泛型编程与STL设计思想
开发语言·c++·算法