leetcode hot100刷题日记——28.环形链表2
解答:
方法一:哈希表
class Solution {
public:ListNode *detectCycle(ListNode *head) {//哈希表unordered_set<ListNode *>visited;while(head!=nullptr){if(visited.count(head)){return head;}visited.insert(head);head=head->next;}return nullptr;}
};
时间复杂度:O(N)
空间复杂度:O(N)
方法二:快慢指针
class Solution {
public:ListNode *detectCycle(ListNode *head) {//快慢指针//快指针每次走两步,慢指针每次走一步//假设相遇点是图中紫色点//那么快指针走过的路=a+(b+c)*n+b=a+(n+1)*b+n*c//慢指针走过的路=a+b//快指针走过的路一定是慢指针的两倍//2a+2b=a+(n+1)*b+n*c//a=(n-1)b+nc//由于b+c是环长,所以a=(b+c)(n-1)+c//也就是说,相遇点和入环点之间的距离c+n-1圈环长,也就是从链表头到入环点的距离//我们找到slow和fast指针相遇的时候很容易(slow==fast)//这个时候如果再设置一个指针temp在表头,和慢指针同时每次走一步,那么temp和慢指针相遇的地方就在入环点ListNode *fast=head,*slow=head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;if(slow==fast){ListNode *temp=head;while(temp!=slow){slow=slow->next;temp=temp->next;}return temp;}}return nullptr;}
};
时间复杂度:O(N)
空间复杂度:O(1)