作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/linked-list-cycle/

Total Accepted: 102417 Total Submissions: 277130 Difficulty: Easy

题目描述

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 = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

题目大意

判断单链表里是否有环。

解题方法

双指针

双指针的方法。

思路是两个指针,一个每次走两步,一个每次走一步,循环下去,只要两者能够重逢说明有环。

Java代码如下:

public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode fast = head;
ListNode slow = head;
while(slow!=null){
if(fast.next==null || fast.next.next==null) return false;
fast=fast.next.next;
slow=slow.next;
if(fast==slow) break;
}
return true;
}
}

AC:1ms

看了官方解答之后,发现可以优化,优化如下:

	public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) return false;
ListNode fast = head.next;
ListNode slow = head;
while(slow!=fast){
if(fast.next==null || fast.next.next==null) return false;
fast=fast.next.next;
slow=slow.next;
}
return true;
}
}

我想的是只要走的慢的这个不为空的话,就一直走好了。 官方解答想的是两者不重合就一直走。

二刷,Python。

上python版本的。

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow, fast = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False

三刷,python.

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head: return False
slow, fast = head, head.next
while fast and fast.next:
if fast == slow:
return True
fast = fast.next.next
slow = slow.next
return False

四刷,C++。注意C++里面全部用的是指针操作。代码如下:

/**
* 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) {
if (!head) return false;
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return true;
}
return false;
}
};

保存已经走过的路径

官方解答的HashTable的方法。记录下来哪些已经走了,只要走到之前走过的节点说明有环。

public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> hash=new HashSet();
while(head!=null){
if(hash.contains(head)){
return true;
}else{
hash.add(head);
}
head=head.next;
}
return false;
}
}

AC:10ms

日期

2016/5/2 17:24:37
2018 年 11 月 24 日 —— 周六快乐
2019 年 1 月 11 日 —— 小光棍节?

最新文章

  1. Kinect2.0 for Mac开箱
  2. 一次线上http接口调用不通相关的解决过程
  3. sqlServer数据库插入数据后返回刚插入记录的自增ID
  4. SQL Server数据库性能优化(一)之 优化SQL 语句
  5. android学习笔记25——事件处理Handler
  6. [译]使用AES 256以达到SSL/TLS安全最大化
  7. java.sql.DataTruncation: Data truncation
  8. java.io.FileNotFoundException: class path resource [META-INF/xfire/services.xml] cannot be opened because it does not exist
  9. 使用C/C++编译预处理时须要注意的问题
  10. 再起航,我的学习笔记之JavaScript设计模式18(观察者模式)
  11. Set的常用方法(java)
  12. flask error
  13. 编译问题:&#39;&lt;invalid-global-code&gt;&#39; does not contain a definition for &#39;Store&#39; and no extension method &#39;XXX&#39; accepting a first argument of type &#39;&lt;invalid-global-code&gt;&#39; could be found
  14. C#程序终止问题CLR20R3解决方法
  15. vue子传父多个值
  16. mybatis总结之一
  17. mac下shell给文件名批量加前缀
  18. ReactiveX 学习笔记(6)条件操作符
  19. [VS]VS2010如何使用Visual Studio Online在线服务管理团队资源(在线TFS)
  20. java三方----&gt;html解析jsoup的使用

热门文章

  1. 【Perl】如何安装Bioperl模块?
  2. nginx_日志
  3. 【模板】二分图最大匹配(匈牙利算法)/洛谷P3386
  4. 浅讲.Net 6 之 WebApplicationBuilder
  5. Output of C++ Program | Set 16
  6. 如果你不想让pthread_join阻塞你的进程,那么请调用pthread_detach
  7. sf02_选择排序算法Java Python rust 实现
  8. js将数字转为千分位/清除千分位
  9. AI 2021 年度报告
  10. 5、Redis五大基本数据类型——String类型