Hashmap vs LinkedList


  • 0
    D

    I tried the o(n) method, but find it works when I used hashset while using arraylist, there is some error. in this case, they should be equivalent right? could anyone explain why arraylist doesnt work?

    Thanks!

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null){
                return false;
            }
          ArrayList<ListNode> record = new ArrayList<ListNode>();
            while(head != null){
                if(record.contains(head)){
                    return true;
                }
                record.add(head);
                head = head.next;
            }
            return false;
            
        }
    }

Log in to reply
 

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