138. Copy List with Random Pointer

这道题咋看挺复杂,又要clone node还要clone random link,但其实只要用一个HashMap就可以轻松解决,以下是我的算法,先clone node和node的next link,然后clone node的random link,时间复杂度O(n):

    public Node copyRandomList(Node head) {
        if (head == null)
            return null;
        Map<Node, Node> map = new HashMap<>();
        Node res = new Node(head.val);
        clone(head, res, map);
        randomLink(head, res, map);
        return res;
    }

    private void clone(Node oldNode, Node newNode, Map<Node, Node> map) {
        map.put(oldNode, newNode);
        if (oldNode.next != null) {
            newNode.next = new Node(oldNode.next.val);
            clone(oldNode.next, newNode.next, map);
        }
    }

    private void randomLink(Node oldNode, Node newNode, Map<Node, Node> map) {
        if (oldNode.random != null) {
            newNode.random = map.get(oldNode.random);
        }
        if (oldNode.next != null) {
            randomLink(oldNode.next, newNode.next, map);
        }
    }

 

上一篇:tf.variable_scope('rnn')解析


下一篇:莫烦Tensorflow学习代码九(手写数字识别MNIST CNN学习)