讨论/《图解算法数据结构》 - 剑指 Offer 35 题目解析/
《图解算法数据结构》 - 剑指 Offer 35 题目解析

用 哈希表+递归 做的,时间很快 0ms ,内存占用很多 38M - -

/*
// 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> nodeMap = new HashMap();
    public Node copyRandomList(Node head) {
        if (head == null) {
            return head;
        }
        Node node = new Node(head.val);
        if (head.next == null && head.random != null) {
            node.random = node;
            return node;
        }

        recur(node, head);
        return node;
    }

    public void recur(Node cur, Node head) {
        if (head == null){
            cur.next = null;
            return;
        }
        nodeMap.put(head,cur);

        if (head.next != null){
            Node next = new Node(head.next.val);
            cur.next = next;
            recur(next, head.next);
        }
        cur.random = nodeMap.get(head.random);
    }
}
1
展开全部 11 讨论