(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
}
相关推荐
YA33320 小时前
java设计模式二、工厂
java·开发语言·设计模式
今天头发还在吗20 小时前
【Go】:mac 环境下GoFrame安装开发工具 gf-cli——gf_darwin_arm64
macos·golang·go·gf-cli
金色天际线-20 小时前
Nginx 优化与防盗链配置指南
java·后端·spring
逐雨~20 小时前
9.8C++作业
开发语言·c++
我爱挣钱我也要早睡!21 小时前
Java 复习笔记
java·开发语言·笔记
AD钙奶-lalala1 天前
Mac OS上搭建 http server
java
皮皮林5511 天前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
利刃大大1 天前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
weixin_456904271 天前
Spring Boot 用户管理系统
java·spring boot·后端