Help!!! LeetCode 138: why Map accept but HashMap NOT accept?


  • 2
    A

    Below are two methods, there're only 2 differences: at line 2 and 5. Method 1 uses HashMap and method 2 uses Map.

    LeetCode runtime result showed Map accepted but HashMap NOT, it showed 'java.lang.StackOverflowError'!!!

    Can someone tell me the reason?

    method 1:

    public RandomListNode copyRandomList(RandomListNode head) {
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        return copyRandomListRecursive(head, map);
    }
    public RandomListNode copyRandomListRecursive(RandomListNode head, HashMap<RandomListNode, RandomListNode> map) {
        if (head == null) {
            return null;
        }
        if (map.containsKey(head)) {
            return map.get(head);
        }
        RandomListNode node = new RandomListNode(head.label);
        map.put(head, node);
        node.next = copyRandomListRecursive(head.next, map);
        node.random = copyRandomListRecursive(head.random, map);
        return node;
    }
    

    method 2:

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

  • 0
    M

    I got the same issue and I have no idea why this happened!
    Have you figured this out?


Log in to reply
 

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