(LeetCode 面试经典 150 题) 138. 随机链表的复制 (哈希表)

题目:138. 随机链表的复制



思路:哈希表,时间复杂度0(n)。

C++版本:

cpp 复制代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    unordered_map<Node *,Node *> mp;
    Node* copyRandomList(Node* head) {
        if(head==nullptr) return head;
        if(!mp.count(head)){
            Node *tmp= new Node(head->val);
            mp[head]=tmp;
            // 注意,在递归前,要先用哈希表记录tmp
            tmp->next=copyRandomList(head->next);
            tmp->random=copyRandomList(head->random);
            
        }
        return mp[head];
    }
};

JAVA版本:

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 {
    Map<Node,Node> mp=new HashMap<>();
    public Node copyRandomList(Node head) {
        if(head==null) return head;
        if(!mp.containsKey(head)){
            Node tmp=new Node(head.val);
            mp.put(head,tmp);
            tmp.next=copyRandomList(head.next);
            tmp.random=copyRandomList(head.random);
        }
        return mp.get(head);
    }
}

GO版本:

go 复制代码
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Next *Node
 *     Random *Node
 * }
 */
var mp map[*Node]*Node =map[*Node]*Node{}
func copyRandomList(head *Node) *Node {
    if head ==nil {
        return head
    }
    if x,ok :=mp[head]; ok{
        return x
    }
    tmp := &Node{ Val:head.Val }
    mp[head]=tmp
    tmp.Next=copyRandomList(head.Next)
    tmp.Random=copyRandomList(head.Random)
    return tmp
}
相关推荐
一叶飘零_sweeeet21 小时前
深入拆解 Java CAS:从底层原理到 ABA 问题实战
java·cas·并发编程
walking95721 小时前
Vue3 日历组件选型指南:五大主流方案深度解析
前端·vue.js·面试
StackNoOverflow21 小时前
Spring Security权限控制框架详解
java·数据库·sql
yaaakaaang21 小时前
九、装饰器模式
java·装饰器模式
d_dreamer21 小时前
SeaTunnel推荐Maven版本
java·maven
清心歌21 小时前
记一次系统环境变量更改后在IDEA中无法读取新值的排查过程
java·后端·intellij-idea·idea
大尚来也21 小时前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
dong__csdn21 小时前
jdk添加信任证书
java·开发语言
songyuc21 小时前
BM2『链表内指定区间反转』学习笔记
学习·链表
hhcccchh21 小时前
1.1 HTML 语义化标签(header、nav、main、section、footer 等)
java·前端·html