(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
}
相关推荐
BS_Li11 分钟前
用哈希表封装unordered_set和unordered_map
数据结构·c++·哈希算法·散列表
MFine17 分钟前
Rhythmix(流式数据规则表达式),一行就够了!
java·物联网·数据分析
waves浪游41 分钟前
C++多态
开发语言·c++
华仔啊1 小时前
面试官问:流量突然暴增100倍,系统怎么扛?我的方案是...
java
一只乔哇噻1 小时前
java后端工程师进修ing(研一版‖day50)
java·开发语言
快码加编~1 小时前
无法解析插件 org.apache.maven.plugins:maven-site-plugin:3.12.1
java·学习·maven·intellij-idea
aramae1 小时前
快速排序的深入优化探讨
c语言·开发语言·c++·算法·排序算法
托比-马奎尔1 小时前
Maven学习
java·学习·maven
znhy@1231 小时前
十一、Maven web项目的构建
java·maven
paopao_wu1 小时前
Spring AI 从入门到实战-目录
java·人工智能·spring