๐ŸŒ• ๅ‰‘ๆŒ‡ Offer 35. ๅคๆ‚้“พ่กจ็š„ๅคๅˆถ

ๅžไฝ›็ซฅๅญ2022ๅนด10ๆœˆ10ๆ—ฅ
  • algorithm
  • List
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ• ๅ‰‘ๆŒ‡ Offer 35. ๅคๆ‚้“พ่กจ็š„ๅคๅˆถ

้šพๅบฆ: ๐ŸŒ•

้—ฎ้ข˜ๆ่ฟฐ

img_47.png


่งฃๆณ•

/*
// 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 {
    public Node copyRandomList(Node head) {
        // ๆ€่ทฏ๏ผš
        // HashMap ๅญ˜ๅ‚จ ๅŽŸ่Š‚็‚น - ๆ–ฐ่Š‚็‚น
        if(head == null) {
            return null;
        }
        HashMap<Node, Node> map = new HashMap<>();
        Node res = new Node(-1);
        Node pre = res;
        Node cur = head;
        while(cur != null) {
            Node node = new Node(cur.val); // ๆ–ฐๅคๅˆถ่Š‚็‚น
            map.put(cur, node);
            pre.next = node;
            pre = node;
            cur = cur.next;
        }
        // ๅกซๅ…… rand ่Š‚็‚น
        cur = head;
        while(cur != null) {
            if(cur.random != null) {
                Node origRand = cur.random;
                Node node = map.get(cur);
                Node rand = map.get(origRand);
                node.random = rand;
                // System.out.println(cur.val + "  " + origRand.val + "  " + node.val + "  " + rand.val);
            }
            cur = cur.next;
        }
        return res.next;
    }
}

่พ“ๅ‡บ

img_46.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/10/10 ไธ‹ๅˆ8:43:48
่ดก็Œฎ่€…: liuxianzhishou