Java 11ms solution with HashSet and 1ms solution without extra space


  • 3
    R
        public boolean hasCycle(ListNode head) {
    		if (head == null || head.next == null)
    			return false;
    		HashSet<ListNode> nodeSet = new HashSet<>();
    		while(head != null) {
    			if (nodeSet.contains(head))
    				return true;
    			nodeSet.add(head);
    			head = head.next;
    		}
    		return false;
    	}
    	
    	public boolean hasCycleNoExtraSpace(ListNode head) {
    		if (head == null || head.next == null) 
    			return false;
    		ListNode p = head;
    		ListNode q = head;
    		while(q != null && q.next != null) {
    			p = p.next;
    			q = q.next.next;
    			if (p == q)
    				return true;
    		}
    		return false;
    	}

  • 0
    W
    This post is deleted!

Log in to reply
 

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