c++ codes in 9ms


  • 0
    _

    My solution using 2 pointers cost 9ms:

    '''
    bool hasCycle(ListNode head)
    {
    ListNode
    fast = head;
    ListNode* slow = head;
    while (fast != NULL)
    {
    slow = slow->next;
    if (fast->next == NULL)
    return false;
    fast = fast->next->next;
    if (slow == fast)
    return true;
    }
    if (fast == NULL)
    return false;
    }
    ''''

    while another solution cost 12ms
    "'
    bool hasCycle(ListNode* head) {
    if (head == NULL)
    return false;
    ListNode* fast = head->next;
    ListNode* slow = head;
    while (fast != slow) {
    if (fast == NULL || fast->next == NULL)
    return false;
    fast = fast->next->next;
    slow = slow->next;
    }
    return true;
    }
    ''''
    Is there anyone can explan it?


Log in to reply
 

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