(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
}
相关推荐
C雨后彩虹11 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..11 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X11 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
元Y亨H13 小时前
Nacos - 服务发现
java·微服务
微露清风13 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi022713 小时前
Java趣闻
java
CSARImage14 小时前
C++读取exe程序标准输出
c++
一只小bit14 小时前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
阿波罗尼亚14 小时前
Tcp SSE Utils
android·java·tcp/ip
一条大祥脚14 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法