Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

Does everyone solved it with O(n) complexity?

0 votes
158 views

My code is O(n2) and was told time exceeded

asked 1 day ago in Linked List Cycle by [email protected] (160 points)

Could please detail your solution and your analysis about the time complexity of your solution? It will help others see what might block you.

i define a variable called flags ,flags is a big number,(ie flags=2^31)

then iterate from the head node... then let the value of node which had iterated be flags ....so when i find the value of the current node is falgs ...that means the list has a cycle

3 Answers

+2 votes

This is similar with CC150 question. You may try "fast runner and slow runner" solution. Fast pointer runs 2 steps at a time and slow runner runs 1 step at a time. They both start from beginning. If faster runner catches slow runner some time, it means linked list has a circle.

answered 1 day ago by swang511 (180 points)

Great, I never thought about this before.

This is also my first time hearing about the fast runner slow runner. I shall add it to my toolbox.

0 votes

Cool idea of slow/fast pointer !

or you could record the ith(i = 1,2,4,8..........) ListNode* and compare it to your iterating ListNode*

answered 6 hours ago by supdileo (140 points)
0 votes
public static int nil=(int)Math.pow(2, 30);
public boolean hasCycle(ListNode head) {
        if(head==null)
        return false;
    ListNode temp=head;
    boolean flags=false;
    temp.val=nil;
    while(temp.next!=null)
    {
        temp=temp.next;
        if(temp.val==nil)//that means this node has been iterated before, that means the list has a cycle   
        {
            flags=true;
            break;
        }
        else
        {
            temp.val=nil;
        }
    }
    return flags;
}
answered 3 hours ago by codding (140 points) 1 flag

Could you please update your answer with some words to tell your brief idea? Like your comment on the question? Please do not answer a question thru its comment, just give a answer. Thanks!


...