码迷,mamicode.com
首页 > 其他好文 > 详细

141.Linked List Cycle

时间:2017-10-18 16:07:59      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:open   指针   题解   ret   一个   判断   node   problem   复杂度   

题目链接:https://leetcode.com/problems/linked-list-cycle/description/

题目大意:给出一个链表,判断该链表是否有环,空间复杂度最好控制在o(1)

这个题没有给测试用例,导致没太明白题目意思,看了题解,用了两种方法示例如下:

法一(借鉴):利用两个指针,一个指针步长为2,一个指针步长为1,若链表中有环,则两个指针同时走,在某一时刻一定会走到一起;若链表中没有环,则两个指针一定会走到null,代码如下(耗时1ms):

技术分享
 1     public boolean hasCycle(ListNode head) {
 2         ListNode fast = head;
 3         ListNode slow = head;
 4         while(fast != null && slow != null && fast.next != null) {
 5             slow = slow.next;
 6             fast = fast.next.next;
 7             if(slow == fast) {
 8                 return true;
 9             }
10         }
11         return false;
View Code

法二(借鉴):利用set集合中的contains,判断是否有两个相同的结点在集合中,如果有,则有环,代码如下(耗时10ms):

技术分享
 1         Set<ListNode> list = new HashSet<>();
 2         while(head != null) {
 3             if(list.contains(head)) {
 4                 return true;
 5             }
 6             else {
 7                 list.add(head);
 8                 head = head.next;
 9             }
10         }
11         return false;    
View Code

 

141.Linked List Cycle

标签:open   指针   题解   ret   一个   判断   node   problem   复杂度   

原文地址:http://www.cnblogs.com/cing/p/7686993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!