I don't know why my solution exceed the time limit?


  • 0
    J
    public boolean hasCycle(ListNode head) {
        ListNode temp=head;
        if(head==null) {
        	return false;
        }
        while(temp.next!=null) {
        	
        	if(temp.next==head) {
        		return true;
        	}
        	temp=temp.next;
        }
       
        return false;
    }
    

    I think my solution is right,and is similar to some solutions that posted by others.But it's always "Time Limit Exceed",I don't get it.


  • 0

    A cycle doesn't necessarily involve the head. Think of writing a "6" from the top.


  • 0
    J

    Thanks.I get it.So the last element may be related to others,but not head,right?What do you mean by writing a "6" from the top?


  • 0

    What do you mean with "last element"? If there's a cycle, there is no last element.

    With writing a "6" from the top I mean you take a pen, you take a paper, and then you write a "6". From the top. Not from the middle (some people might do that, so I had to clarify).

    If you do that, you start drawing a line and eventually draw a cycle, but that cycle doesn't involve the point where you started drawing.


  • 0
    J

    I get it.Thank you very much.


Log in to reply
 

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