Is there any faster solution?


  • 0
    L
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            if (head == NULL)
                return NULL;
            ListNode *fast = head, *slow = head;
            while (fast->next != NULL && fast->next->next != NULL)
            {
                fast = fast->next->next;
                slow = slow->next;
                if (fast == slow)
                {
                    slow = head;
                    while (fast != slow)
                    {
                        fast = fast->next;
                        slow = slow->next;
                    }
                    return fast;
                }
            }
            return NULL;
            
        }
    };
    

    I submitted the above code. And saw that my solution is very slow. More faster solution are there.

    But, is there really more better solution ? Whether the faster solutions need more space complexity or not?


  • 0

    How long does it cost? I tried your code, 12ms is not slow at all. You can see there is no faster submission.


Log in to reply
 

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