Time Limit Exceeded WHY?


  • 0
    M

    Language: c
    Status: Time Limit Exceeded

    Last executed input:
    [3,2,0,-4]
    tail connects to node index 1

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        struct ListNode *p = head;
        while(p)
        {
            if(p->next == head)
            {
                return true;
            }
            p = p->next;
            
        }
        return false;
    }
    

    Language: c
    Submission Result: Runtime Error

    Last executed input:
    [1,2]
    tail connects to node index 0

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        struct ListNode *p = head;
        while(p)
        {
            if(p->next == head)
            {
                return true;
            }
            else
            {
                struct ListNode *tmp = p;
                p = p->next;
                tmp->next = head;
            }
        }
        return false;
    }
    

    Language: C++
    Submission Result: Accepted

    Code as above but accepted, why?

    class Solution {
    public:
        bool hasCycle(struct ListNode *head) {
            struct ListNode *p = head;
            while(p)
            {
                if(p->next == head)
                {
                    return true;
                }
                else
                {
                    struct ListNode *tmp = p;
                    p = p->next;
                    tmp->next = head; //why do this?
                }
            
            }
            return false;
        }
    };
    

Log in to reply
 

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