题目描述
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
}
};
题目解析
快慢指针
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *fast = head;
ListNode *slow = head;
do{
if(fast == nullptr || fast->next == nullptr){
return nullptr;
}
fast = fast->next->next;
slow = slow->next;
}while (fast != slow);
slow = head;
while (fast != slow){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
hash表
如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
std::set<ListNode *> set;
ListNode *curr = head;
while (curr != nullptr){
if(set.count(curr)){
return curr;
}
set.insert(curr);
curr = curr->next;
}
return nullptr;
}
};
题目 | 思路 |
---|---|
leetcode:141. 链表是否存在环 Linked List Cycle | |
leetcode:142. 环形链表的入环节点 II Linked List Cycle II | |
leetcode:287.无序数组出现多次的数字(一个数出现多次,其他数出现一次或者零次) (数组数据范围在[1, n],数据长度为n+1) Find the Duplicate Number | 因为不允许修改原数组,所以不能用标记法。而一般对于链表,数组中要求找重复的数字或者节点,都可以考虑用快慢指针的方法来解,也就是入环节点就是那个重复的数 |