[LeetCode] Linked List Cycle 单链表中的环

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

Follow up:
Can you solve it without using extra space?

 

开始以为这道题只需要注意不使用额外空间即可,于是写了个时间复杂度为O(n^2)暴力搜索算法,如下:

 

/**
 * Dumped, Time Limit Exceeded
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next) return false;
        ListNode *pre = head;
        ListNode *cur = head->next;
        while (cur) {
            pre = head;
            while (cur->next != pre && pre != cur) {
                pre = pre->next;
            }
            if (cur->next == pre && pre != cur) return true;
            cur = cur->next;
        }
        return false;
    }
};

 

可是OJ还是不给通过,原因是Time Limit Exceeded,还是需要把时间复杂度缩小的O(n)才行,于是上网搜各位大神的方法,发现果然很神奇。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。实在是太巧妙了,要是我肯定想不出来。代码如下:

 

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = slow;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) break;
        }
        if (!fast || !fast->next) return false;
        return true;
    }
};

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)