当前位置:网站首页>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 .
边栏推荐
- Differences between x86 and x64
- The final of the sixth season of 2022 perfect children's model Hefei division came to a successful conclusion
- Huawei equipment is configured with medium-sized network WLAN basic services
- 各種級數(調和、幾何)總結
- Verilog first experience
- Target tracking [single target tracking (vot/sot), target detection, pedestrian re identification (re ID)]
- How to recite words in tables
- The difference and usage of JS for in loop and for of loop
- 各种级数(调和、几何)总结
- [untitled]
猜你喜欢

51单片机中断与定时器计数器,基于普中科技HC6800-ESV2.0

一个高频问题,三种模型思维来破解此风控难题

802.11--802.11n协议 PHY

Transformer details

闭关修炼(二十五)基础web安全

对话| 数字时代,隐私计算的发展前景与挑战

Matlab 用法

人民链鲍大伟:打破壁垒,建立全域数据治理共享及应用平台

Huawei equipment is configured with medium-sized network WLAN basic services

Wallpaper applet source code double ended wechat Tiktok applet
随机推荐
NLP annotation tool: label studio realizes multi-user collaborative marking
使用adb命令调试夜神模拟器
考研英语易混词整理【闪过】
Set up Jenkins environment and automatically associate packaged project jars for automatic release
通过ELO机制衡量各类对弈活动水平
关于SQL语句的大小写
壁纸小程序源码双端微信抖音小程序
How to recite words in tables
Sorting out easily confused words in postgraduate entrance examination English 【 flash 】
Matlab 用法
各种级数(调和、几何)总结
自注意力机制超级详解(Self-attention)
闭关修炼(二十四)浅入了解跨域问题
The final of the sixth season of 2022 perfect children's model Hefei division came to a successful conclusion
A review of visual SLAM methods for autonomous driving vehicles
启牛学堂让开的证券账户是真的安全靠谱吗?
2022第六季完美童模 合肥赛区 决赛圆满落幕
分布式数字身份的几个“非技术”思考
Np5 formatted output (III)
ThreadLocal线程变量



