1. 程式人生 > 其它 >2021-1-21 141.環形連結串列

2021-1-21 141.環形連結串列

技術標籤:力扣刷題

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* slow=head;
        if(slow==NULL){
            return false;
        }
        ListNode* fast=head->next;
        if(fast==NULL){
            return false;
        }
        while(fast!=NULL&&fast-
>next!=NULL){//終止條件注意 if(fast!=slow){ fast=fast->next->next; slow=slow->next; } else{ return true; } } return false; } };

官方題解:
本方法需要讀者對「Floyd 判圈演算法」(又稱龜兔賽跑演算法)有所瞭解。

假想「烏龜」和「兔子」在連結串列上移動,「兔子」跑得快,「烏龜」跑得慢。當「烏龜」和「兔子」從連結串列上的同一個節點開始移動時,如果該連結串列中沒有環,那麼「兔子」將一直處於「烏龜」的前方;如果該連結串列中有環,那麼「兔子」會先於「烏龜」進入環,並且一直在環內移動。等到「烏龜」進入環時,由於「兔子」的速度快,它一定會在某個時刻與烏龜相遇,即套了「烏龜」若干圈。

我們可以根據上述思路來解決本題。具體地,我們定義兩個指標,一快一滿。慢指標每次只移動一步,而快指標每次移動兩步。初始時,慢指標在位置 head,而快指標在位置 head.next。這樣一來,如果在移動的過程中,快指標反過來追上慢指標,就說明該連結串列為環形連結串列。否則快指標將到達連結串列尾部,該連結串列不為環形連結串列。

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

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

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

hash表法(空間複雜度為O(n)):
最容易想到的方法是遍歷所有節點,每次遍歷到一個節點時,判斷該節點此前是否被訪問過。

具體地,我們可以使用雜湊表來儲存所有已經訪問過的節點。每次我們到達一個節點,如果該節點已經存在於雜湊表中,則說明該連結串列是環形連結串列,否則就將該節點加入雜湊表中。重複這一過程,直到我們遍歷完整個連結串列即可。

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set<ListNode*> seen;
        while (head != nullptr) {
            if (seen.count(head)) {
                return true;
            }
            seen.insert(head);
            head = head->next;
        }
        return false;
    }
};

作者:LeetCode-Solution
連結:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

注:
①注意快慢指標的初值和迴圈中止條件
②hash表法也要看一看