当前位置:网站首页>Leetcode (142) - circular linked list II
Leetcode (142) - circular linked list II
2022-06-29 08:43:00 【SmileGuy17】
Leetcode(142)—— Circular list II
subject
Given the head node of a linked list head , Return to the first node of the link where the list begins to enter . If the list has no links , Then return to null.
If there is a node in the linked list , It can be done by continuously tracking next The pointer reaches again , Then there is a ring in the linked list . To represent a ring in a given list , The evaluation system uses an integer pos To indicate where the end of the list is connected to the list ( Index from 0 Start ). If pos yes -1, There are no links in the list . Be careful :pos Not passed as an argument , Just to identify the actual situation of the linked list .
No modification allowed Linked list .
Example 1:
Input :head = [3,2,0,-4], pos = 1
Output : The return index is 1 The linked list node of
explain : There is a link in the list , Its tail is connected to the second node .
Example 2:
Input :head = [1,2], pos = 0
Output : The return index is 0 The linked list node of
explain : There is a link in the list , Its tail is connected to the first node .
Example 3:
Input :head = [1], pos = -1
Output : return null
explain : There are no links in the list .
Tips :
- The number of nodes in the list is in the range [ 0 , 1 0 4 ] [0, 10^4] [0,104] Inside
- − 1 0 5 -10^5 −105 <= Node.val <= 1 0 5 10^5 105
- pos The value of is − 1 -1 −1 Or a valid index in a linked list
Advanced : Can you use O ( 1 ) O(1) O(1) The algorithm of space complexity solves this problem ?
Answer key
Method 1 : Hashtable
Ideas
A very intuitive idea is : We Traverse each node in the linked list , And write it down ; Once the node traversed before is encountered again , You can determine that there is a link in the linked list . With the help of hash table, it is very convenient to realize .
Code implementation
Leetcode Official explanation :
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;
}
};
Complexity analysis
Time complexity : O ( N ) O(N) O(N), among N N N Is the number of nodes in the linked list . We just need to access every node in the linked list .
Spatial complexity : O ( N ) O(N) O(N), among N N N Is the number of nodes in the linked list . We need to save each node in the linked list in the hash table .
Method 2 : Speed pointer
Ideas
We use the speed pointer , fast \textit{fast} fast And slow \textit{slow} slow. They all start at the head of the linked list . And then , slow \textit{slow} slow The pointer moves back one position at a time , and fast \textit{fast} fast The pointer moves back two positions . If there are rings in the list , be fast \textit{fast} fast The pointer will end up with slow \textit{slow} slow The pointer meets in the ring , And It must meet before the slow pointer reaches the end of the linked list .
As shown in the figure below , Let the length of the outer part of the link in the linked list be a a a. slow \textit{slow} slow After the pointer enters the ring , Gone again b b b The distance between fast \textit{fast} fast meet . here , fast \textit{fast} fast The pointer has gone through the ring n n n circle , therefore Quick pointer fast \textit{fast} fast The total distance traveled is a + n ( b + c ) + b = a + ( n + 1 ) b + n c a+n(b+c)+b=a+(n+1)b+nc a+n(b+c)+b=a+(n+1)b+nc.
According to the meaning , Anytime , fast \textit{fast} fast The distance traveled by the pointer is slow \textit{slow} slow Pointer 2 2 2 times . therefore , We have the following equation :
a + ( n + 1 ) b + n c = 2 ( a + b ) * a = c + ( n − 1 ) ( b + c ) a+(n+1)b+nc=2(a+b) \implies a=c+(n-1)(b+c) a+(n+1)b+nc=2(a+b)*a=c+(n−1)(b+c)
With a = c + ( n − 1 ) ( b + c ) a=c+(n-1)(b+c) a=c+(n−1)(b+c) The equivalence of , We will find that : Subtract from inner ring b b b The length of plus n − 1 n-1 n−1 Ring length of circle , Exactly equal to the distance from the head of the linked list to the ring entry point .
therefore , If I found slow \textit{slow} slow And fast \textit{fast} fast When we met , Let's use an extra pointer ptr \textit{ptr} ptr. start , It points to the head of the linked list ; And then , It and slow \textit{slow} slow Move back one position at a time . Final , They will meet at the entry point .
Why does the slow pointer meet the fast pointer before the first lap of the loop is completed ?
set up The length of the ring by A A A, When the slow pointer enters the ring, the position of the fast pointer in the ring B B B( The value range is [ 0 , A − 1 ] [0, A-1] [0,A−1]),
When the fast and slow hands meet [ The slow pointer walked in the ring C C C], Yes
C % A = ( B + 2C) % A, Equivalent to
A n + C = B + 2 C An + C = B + 2C An+C=B+2C, Merge to
C = A n − B C = An - B C=An−B
When n = 1 n=1 n=1 when , 0 < = C < A 0 <= C < A 0<=C<A
so The slow pointer must meet the fast pointer before the first circle of the loop is completed
Code implementation
Leetcode Official explanation :
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr) {
slow = slow->next;
if (fast->next == nullptr) break;
else fast = fast->next->next;
if (fast == slow) {
fast = head; // At this point, the fast pointer is useless , Used as a temporary variable
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
return nullptr;
}
};
Complexity analysis
Time complexity :$O(N), among N N N Is the number of nodes in the linked list . In the initial judgment of whether the fast and slow pointers meet , slow \textit{slow} slow The distance traveled by the pointer will not exceed the total length of the linked list ; Then when looking for the entry point , The distance traveled will not exceed the total length of the linked list . therefore , The total execution time is O ( N ) + O ( N ) = O ( N ) O(N)+O(N)=O(N) O(N)+O(N)=O(N).
Spatial complexity : O ( 1 ) O(1) O(1). We only used slow , fast \textit{slow}, \textit{fast} slow,fast Two pointers .
边栏推荐
猜你喜欢
随机推荐
How to recite words in tables
Batch processing of experimental contact angle data matlab analysis
Voice annotation tool: Praat
闭关修炼(二十五)基础web安全
Résumé des différentes séries (harmoniques, géométriques)
NP5 格式化输出(三)
2022第六季完美童模 合肥赛区 决赛圆满落幕
机器人代码生成器之Robcogen使用教程
Simple use of AWS elastic Beanstalk
重磅发布 | 《FISCO BCOS应用落地指南》
Feature selection: maximum information coefficient (MIC) [used to measure the degree of correlation between two variables X and y, linear or nonlinear strength, commonly used for feature selection of
2022 spring summer collection koreano essential reshapes the vitality of fashion
The final of the sixth season of 2022 perfect children's model Hefei division came to a successful conclusion
Speech synthesis: overview [generation task of unequal length sequence relation modeling]
Set up Jenkins environment and automatically associate packaged project jars for automatic release
51单片机中断与定时器计数器,基于普中科技HC6800-ESV2.0
【微服务|OpenFeign】openfeign的超时时间
特征选择:最大信息系数(MIC;Maximal Information Coefficient)【用于衡量两个变量X和Y之间的关联程度,线性或非线性的强度,常用于机器学习的特征选择】
语音标注自动音段对齐工具SPPAS使用笔记
考研英语易混词整理【闪过】









![[hcie TAC] question 5-2](/img/a5/308aa2cced4cba59354c576a07e3c0.jpg)


