(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
}
相关推荐
多米Domi01136 分钟前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
饺子大魔王的男人37 分钟前
Remote JVM Debug+cpolar 让 Java 远程调试超丝滑
java·开发语言·jvm
_F_y7 小时前
MySQL用C/C++连接
c语言·c++·mysql
兩尛7 小时前
c++知识点2
开发语言·c++
xiaoye-duck7 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Azure_withyou8 小时前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月8 小时前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
Hx_Ma168 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode9 小时前
原子操作类LongAdder
java·开发语言
舟舟亢亢9 小时前
Java集合笔记总结
java·笔记