Java solution using hashset


  • 0
    R
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null) return null;
            ListNode iter = head;
            Set<ListNode> mp = new HashSet<ListNode>();
            while(iter != null) {
                if(mp.contains(iter)){
                    return iter;
                }
                mp.add(iter);
                iter = iter.next;
            }
            return null;
        }
    }
    

    Could anyone tell me why this method is slower than two pointer?
    Thanks.


Log in to reply
 

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