1 round solution with HashMap


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

Log in to reply
 

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