Java hashmap with one-pass


  • 0
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if (head == null) {
                return null;
            }
            Map<RandomListNode, RandomListNode> map = new HashMap<>();
            map.put(null, null);
            map.put(head, new RandomListNode(head.label));
            RandomListNode node = head;
            while (node != null) {
                if (!map.containsKey(node.random)) {
                    map.put(node.random, new RandomListNode(node.random.label));
                }
                map.get(node).random = map.get(node.random);
                if (!map.containsKey(node.next)) {
                    map.put(node.next, new RandomListNode(node.next.label));
                }
                map.get(node).next = map.get(node.next);
                node = node.next;
            }
            return map.get(head);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.