链表-leetcode 141 Linked List Cycle
来源:互联网 发布:linux 合并文件夹 编辑:程序博客网 时间:2024/06/07 01:44
题目链接:Linked List Cycle
题解:
/*
思路:借助一个set,将访问过的节点存储到set中,如果再次访问到set,则返回true,否则返回false;
Time Complexity:O(N)
Space Complexity:(N)
*/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <set>class Solution {public: bool hasCycle(ListNode *head) { if(!head)return false; set<ListNode *>listSet; while(head){ if(listSet.find(head)!=listSet.end())return true; else{ listSet.insert(head); head=head->next; } } return false; }};
题目follow up:能否不用额外的空间完成任务,当然也是可以的
思路:借助链表的好帮手,快慢指针。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution{ public: bool hasCycle(ListNode* head){ /* Time Complexity:O(N) */ if(!head)return false; ListNode *fast=head; ListNode *slow=head; while(fast->next && fast->next->next){ slow=slow->next; fast=fast->next->next; if(slow==fast)return true; } return false; } }
阅读全文
0 0
- 链表-leetcode 141 Linked List Cycle
- Leetcode#141(链表)-Linked List Cycle
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [leetcode 141] Linked List Cycle
- [leetcode]141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode[141]-Linked List Cycle
- leetcode-141-Linked List Cycle
- [Leetcode 141] Linked List Cycle
- leetcode 141: Linked List Cycle
- [Leetcode]#141 Linked List Cycle
- leetCode #141 Linked List Cycle
- leetcode: (141) Linked List Cycle
- [leetcode] #141 Linked List Cycle
- 举例说明Java中代码块的执行顺序
- 将图片( PNG, BMP, JPEG )转成 svg, 再转成字体图标
- html 去调边框阴影
- 一个屌丝程序猿的人生(八)
- java中Set集合是如何识别相同对象的
- 链表-leetcode 141 Linked List Cycle
- 你还在对着手机干唱?k歌神器挑选法则
- Hibernate中session.get()方法的作用?
- Unity3d架构之-Unity MVC框架 StrangeIoC
- 关于LabVIEW视觉ROI的读取与存储
- 项目PM思考
- redis开多实例
- swift-工具类-日期(类扩展)
- 浅析云计算背景下云存储的优势与劣势