
[Easy] 141. Linked List Cycle
发布日期:2021-05-07 18:21:25
浏览次数:25
分类:精选文章
本文共 1816 字,大约阅读时间需要 6 分钟。
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1Output: trueExplanation: There is a cycle in the linked list, where tail connects to the second node.
Input: head = [1], pos = -1Output: falseExplanation: There is no cycle in the linked list.
Solution
Hash Table
Runtime: 24 ms, faster than 10.66% of C++ online submissions for Linked List Cycle. Memory Usage: 10.5 MB, less than 25.00% of C++ online submissions for Linked List Cycle.
时间、空间复杂度均为O(n)class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL) return false; unordered_mapmap; for(ListNode* p = head; p != NULL; p = p->next){ if(map[p]) return true; map[p] = p; } return false; }};
边建表,边查找。如果之前已经创建过映射,那么说明有Cycle。
Two Pointers
Runtime: 12 ms, faster than 51.39% of C++ online submissions for Linked List Cycle. Memory Usage: 7.9 MB, less than 100.00% of C++ online submissions for Linked List Cycle.
时间复杂度O(n),空间复杂度O(1)class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL || head->next == NULL) return false; ListNode* fast = head->next; ListNode* slow = head; while(fast != slow ){ if(fast == NULL || fast->next == NULL || slow == NULL) return false; else{ slow = slow->next; fast = fast->next->next; } } return true; }};
利用快慢指针:两个不同前进速度的指针,可以假设一个步进为1,一个步进为2。
如果存在Cycle,那么存在某一时刻使得两个指针相遇。否则,指针运行到linked list结尾就会停止。发表评论
最新留言
表示我来过!
[***.240.166.169]2025年03月29日 18时11分53秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Vue新建项目——页面初始化
2021-05-08
Cent OS 7.6 服务器软件安装(这篇博客主要是为了方便我配置云主机的)
2021-05-08
MySQL使用系列文章
2021-05-08
Node.js包使用系列(一)——修改NPM全局下载和缓存路径
2021-05-08
TDengine使用(一)——TDengine下载与安装
2021-05-08
Node.js包使用系列(三)——常用npm包列表
2021-05-08
ubuntu和windows之间无法复制粘贴
2021-05-08
编译Linux内核--制作文件系统--远程调试程序
2021-05-08
启动加载器BootLoader
2021-05-08
力扣239. 滑动窗口最大值
2021-05-08
史上最全Vue的组件传值
2021-05-08
6.14编一个程序,将两个字符串s1和s2比较,不要用strcmp函数。
2021-05-08
如何解决vscode检测到#include错误,请更新includePath。
2021-05-08
1007 Maximum Subsequence Sum (25分) Python解法
2021-05-08
Java纯文本文件显示工具制作
2021-05-08
1035 Password (20分)
2021-05-08
Unity2D Fixed Joint 2D详解
2021-05-08
Unity Shader之路(五)创建第一个顶点/片元着色器?
2021-05-08
L3-008 喊山 (30分) C++ BFS题解
2021-05-08