题目链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { func copyRandomList(_ head: Node?) -> Node? { var dict = [Node:Node]()
func copy(_ node: Node?) -> Node? { guard let node = node else { return nil } if dict[node] == nil { let newHead = Node(node.val) dict[node] = newHead newHead.next = copy(node.next) newHead.random = copy(node.random) } return dict[node] } return copy(head) } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public Node copyRandomList(Node head) { if (head == null) { return null; } Node cur = head; HashMap<Node, Node> map = new HashMap<>(); while (cur != null) { map.put(cur, new Node(cur.val)); cur = cur.next; } cur = head; while (cur != null) { map.get(cur).next = map.get(cur.next); map.get(cur).random = map.get(cur.random); cur = cur.next; } return map.get(head); } }
|
执行用时:176 ms, 在所有 Kotlin 提交中击败了100.00% 的用户
内存消耗:34.6 MB, 在所有 Kotlin 提交中击败了100.00% 的用户
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { fun copyRandomList(node: Node?): Node? { if (node == null) { return null } var cur = node var map = HashMap <Node?, Node?>() while (cur != null) { map[cur] = Node(cur.`val`) cur = cur.next } cur = node while (cur != null) { var temp = map[cur]!! temp.next = map[cur.next] temp.random = map[cur.random] cur = cur.next } return map[node] } }
|