从零开始的LC刷题(35)*: Linked List Cycle 检测链表是否有圈(环)

原题:

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

从零开始的LC刷题(35)*: Linked List Cycle 检测链表是否有圈(环)_第1张图片

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

从零开始的LC刷题(35)*: Linked List Cycle 检测链表是否有圈(环)_第2张图片

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

 

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

一开始用了一个投机取巧(?)的办法,基于染色法但是会修改原环的值,结果:

Success

Runtime: 8 ms, faster than 99.44% of C++ online submissions for Linked List Cycle.

Memory Usage: 9.7 MB, less than 81.96% of C++ online submissions for Linked List Cycle.

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *s;
        s=head;
        while(s!=NULL){
            if(s->val==INT_MAX){return true;}
            s->val=INT_MAX;
            s=s->next;
        }
        return false;
    }
};

更合适的算法是设置两个指针,fast和slow,顾名思义,一个快一点一次移动两个node,结果:

Success

Runtime: 8 ms, faster than 99.44% of C++ online submissions for Linked List Cycle.

Memory Usage: 10 MB, less than 15.90% of C++ online submissions for Linked List Cycle.

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL||head->next==NULL){return false;}
        ListNode *fast,*slow;
        slow=head;
        fast=head->next;
        while(fast!=NULL&&fast->next!=NULL){
            if(slow==fast){return true;}
            slow=slow->next;
            fast=fast->next->next;
        }
        return false;
    }
};

 

你可能感兴趣的:(LEETCODE,C++)