1. 程式人生 > 其它 >【LeetCode】C++ :中等題 - 連結串列 142. 環形連結串列 II

【LeetCode】C++ :中等題 - 連結串列 142. 環形連結串列 II

技術標籤:LeetCode# 連結串列# 雙指標連結串列leetcode演算法

142. 環形連結串列 II

難度中等837

給定一個連結串列,返回連結串列開始入環的第一個節點。如果連結串列無環,則返回null

為了表示給定連結串列中的環,我們使用整數pos來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果pos-1,則在該連結串列中沒有環。注意,pos僅僅是用於標識環的情況,並不會作為引數傳遞到函式中。

說明:不允許修改給定的連結串列。

進階:

  • 你是否可以使用O(1)空間解決此題?

示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:返回索引為 1 的連結串列節點
解釋:
連結串列中有一個環,其尾部連線到第二個節點。

示例2:

輸入:head = [1,2], pos = 0
輸出:返回索引為 0 的連結串列節點
解釋:連結串列中有一個環,其尾部連線到第一個節點。

示例 3:

輸入:head = [1], pos = -1
輸出:返回 null
解釋:連結串列中沒有環。

提示:

  • 連結串列中節點的數目範圍在範圍[0, 104]
  • -105<= Node.val <= 105
  • pos的值為-1或者連結串列中的一個有效索引

1、雜湊表

把訪問過的節點儲存到set裡面,當再次遇到節點已存在時,即為環的入口。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> ust;
        while(head != NULL){
            if(ust.count(head)){
                return head;
            }
            ust.insert(head);
            head = head->next;
        }
        return NULL;
    }
};

2、雙指標 - 快慢指標

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