当前位置:网站首页>Leetcode 0141. circular linked list - three solutions
Leetcode 0141. circular linked list - three solutions
2022-07-28 03:46:00 【Tisfy】
【LetMeFly】 There are three ways to solve :141. Circular list
Force button topic link :https://leetcode.cn/problems/linked-list-cycle/
Give you a list of the head node head , Judge whether there are links in the list .
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 ). Be careful :pos Not passed as an argument . Just to identify the actual situation of the linked list .
If there are rings in the list , Then return to true . otherwise , return false .
Example 1:

Input :head = [3,2,0,-4], pos = 1 Output :true 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 :true explain : There is a link in the list , Its tail is connected to the first node .
Example 3:

Input :head = [1], pos = -1 Output :false explain : There are no links in the list .
Tips :
- The number range of nodes in the linked list is
[0, 104] -105 <= Node.val <= 105posby-1Or one of the lists Valid index .
Advanced : You can use O(1)( namely , Constant ) Does memory solve this problem ?
Method 1 : Hashtable
The principle is simple , Traversing the linked list , Record the traversed nodes with a hash table .
During traversal , If you find that a node already exists in the hash table , It means that this node has been traversed , in other words Ring
Once traversed “next It's empty ” Some node of , It shows that this node is the last node of the linked list , in other words acyclic
- Time complexity O ( n ) O(n) O(n), among n n n Is the number of nodes in the linked list .C++ If you use
unordered_set, Then the complexity of inserting and judging whether it exists is O ( 1 ) O(1) O(1) - Spatial complexity O ( n ) O(n) O(n)
AC Code
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> se;
while (head) {
if (se.count(head))
return true;
se.insert(head);
head = head->next;
}
return false;
}
};
Method 2 : Speed pointer
The reason is not difficult , With two Pointers , The initial positions point to the chain header node .
Each time the fast pointer moves back two nodes , The slow pointer moves one node backward .
If the fast pointer moves to the end of the linked list , It means that the linked list has no ring
If the fast and slow hands meet , It means that the linked list has links
** Be careful :** If there is a ring , Then the fast and slow hands will meet . Because the fast pointer must enter the ring ahead of the slow pointer , Wait for the slow pointer to enter the ring , The fast pointer will catch up with the full pointer ( Because the speed is twice that of the slow pointer ), And I will not jump directly without meeting ( The old position before the slow pointer moves and the new position after it moves 2 2 2 Nodes , Go ahead at one time 2 2 2 Nodes , Must step on one )
- Time complexity O ( n ) O(n) O(n), among n n n Is the number of nodes in the linked list . The speed of a slow pointer is half that of a fast pointer , The fast pointer will catch up with the slow pointer in two laps
- Spatial complexity O ( 1 ) O(1) O(1)
AC Code
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head)
return false;
ListNode *fast = head, *slow = head;
do {
if (!fast->next || !fast->next->next) {
// It's the end
return false;
}
fast = fast->next->next;
slow = slow->next;
} while (fast != slow);
return fast == slow;
}
};
Method 3 : Pass the question for the sake of passing the question
This method is not practical , But you can pass the question with short code .
The title says that the maximum length of the linked list is 1 0 4 10^4 104, So we can count while traversing the linked list , If the number of nodes exceeds 1 0 4 10^4 104, It means that a node has been traversed more than once , That is to say, there are links in the linked list .
- Time complexity O ( n ∨ C ) O(n \vee C) O(n∨C), among n n n Is the number of nodes in the linked list . C C C Is the maximum number of nodes in the linked list ( The title is 1 0 4 10^4 104)
- Spatial complexity O ( 1 ) O(1) O(1)
AC Code
C++
class Solution {
public:
bool hasCycle(ListNode *head) {
int count = 0;
while (head) {
count++;
if (count > 10000)
return true;
head = head->next;
}
return false;
}
};
Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/126017056
边栏推荐
- 服务器内存故障预测居然可以这样做!
- 【OPENVX】对象基本使用之vx_image
- The wonderful use of asemi rectifier bridge GBPC3510 in DC brush motor
- Monotonous stack -- 42. Receiving rain -- a difficult problem that big factories must know
- Data mining-02
- Greedy - 53. Maximum subarray sum
- [paper notes] mobile robot autonomous navigation experimental platform based on deep learning
- WordPress simple mkblog blog theme template v2.1
- Airiot Q & A issue 6 | how to use the secondary development engine?
- CH340 RTS DTR引脚编程驱动OLED
猜你喜欢

Selenium--WEB自动化测试工具

Unity simply implements the dialog function

构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!

数据挖掘-02

Light year admin background management system template

Qt:QMessageBox消息框、自定义信号和槽

Dynamic planning - 62. Different paths

Super nice PHP program source code of nteam official website

Qt:qmessagebox message box, custom signal and slot

Differences among BRD, MRD and PRD
随机推荐
【OPENVX】对象基本使用之vx_distribution
8000 word explanation of OBSA principle and application practice
【OPENVX】对象基本使用之vx_pyramid
SAP UI5 FileUploader 控件深入介绍 - 为什么需要一个隐藏的 iframe 试读版
D2dengine edible tutorial (4) -- draw text
数据挖掘-01
[错题]Concatenation
Integrate SSM to realize search of addition, deletion, modification and query
leetcode刷题:动态规划08(分割等和子集)
What is tor? What is the use of tor browser update?
In depth introduction to sap ui5 fileuploader control - why do you need a hidden iframe trial
Greed 45. Jumping game II
Screenshot of deepstream detection results
LeetCode 0141. 环形链表 - 三种方法解决
贪心——53. 最大子数组和
面试必备杀技:SQL查询专项训练!
LeetCode 0140. 单词拆分 II
695. Maximum area of the island
Day08 redis的基础知识
LeetCode_409_最长回文串