Java Solution (12 ms) using HashSet


  • 0
    A

    If you're allowed to use extra space, this is a pretty concise way to do it.

    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> hashSet = new HashSet<>();
        while(head != null) {
            if(hashSet.contains(head)) return true;
            hashSet.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.