Java using HashSet


  • 0
    Z
    public boolean hasCycle(ListNode head) {
            if(head == null)return false;
            Set<ListNode> set = new HashSet<>();
            while(head != null){
                if(set.contains(head))return true;
                set.add(head);
                head = head.next;
            }
            return false;
        }
    

  • 0
    M

    I think it was not bad.

    But can you improve it without using extra space?


  • 0

    Does Java.util.Set classes use the objects' memory addresses to compare if they are the same object? I'm a little confused on that...


Log in to reply
 

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