作者: 负雪明烛
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 日 —— 小光棍节?

【LeetCode】141. Linked List Cycle 解题报告(Java & Python & C++)的更多相关文章

  1. 【LeetCode】383. Ransom Note 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 [LeetCo ...

  2. 【LeetCode】575. Distribute Candies 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  3. 【LeetCode】136. Single Number 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 异或 字典 日期 [LeetCode] 题目地址:h ...

  4. 【LeetCode】283. Move Zeroes 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:首尾指针 方法二:头部双指针+双循环 方法三 ...

  5. 【LeetCode】143. Reorder List 解题报告(Python)

    [LeetCode]143. Reorder List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  6. 【LeetCode】86. Partition List 解题报告(Python)

    [LeetCode]86. Partition List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:// ...

  7. 【LeetCode】61. Rotate List 解题报告(Python)

    [LeetCode]61. Rotate List 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fux ...

  8. 【LeetCode】376. Wiggle Subsequence 解题报告(Python)

    [LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...

  9. 【LeetCode】649. Dota2 Senate 解题报告(Python)

    [LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...

随机推荐

  1. 【Python小试】使用列表解析式简化代码

    列表解析式的好处: 代码简洁 可读性强 运行快 示例 来自<Python编程>中的一个例子:同时投掷两颗面数不同的骰子(如一个6面的D6和一个10面的D10)n次,统计两个骰子点数之和,并 ...

  2. Notepad++—显示代码对齐是使用了制表符还是空格

    使用Notepad++打开脚本,勾选"显示空格与制表符",此时你会看到代码对齐使用了制表符与空格 右箭头:TAB:空格:点: 参考:https://www.cnblogs.com/ ...

  3. 利用elliipse做相关图

    参考资料:<数据探掘 R语言实战> p65-P68 install.packages("rattle") # 获取实验数据集 install.packages(&quo ...

  4. kafka的安装及使用

    前言花絮 今天听了kafka开发成员之一的饶军老师的讲座,讲述了kafka的前生今世.干货的东西倒是没那么容易整理出来,还得刷一遍视频整理,不过两个比较八卦的问题,倒是很容易记住了. Q:为什么kaf ...

  5. Go语言核心36讲(Go语言实战与应用二十一)--学习笔记

    43 | bufio包中的数据类型(下) 在上一篇文章中,我提到了bufio包中的数据类型主要有Reader.Scanner.Writer和ReadWriter.并着重讲到了bufio.Reader类 ...

  6. 日常Java 2021/10/26

    HashSet基于HashMap来实现的,是一个不允许有重复元素的集合.HashSet 允许有null 值. HashSet是无序的,即不会记录插入的顺序. HashSet不是线程安全的,如果多个线程 ...

  7. SparkStreaming消费Kafka,手动维护Offset到Mysql

    目录 说明 整体逻辑 offset建表语句 代码实现 说明 当前处理只实现手动维护offset到mysql,只能保证数据不丢失,可能会重复 要想实现精准一次性,还需要将数据提交和offset提交维护在 ...

  8. 零基础学习java------37---------mybatis的高级映射(单表查询,多表(一对一,一对多)),逆向工程,Spring(IOC,DI,创建对象,AOP)

    一.  mybatis的高级映射 1  单表,字段不一致 resultType输出映射: 要求查询的字段名(数据库中表格的字段)和对应的java类型的属性名一致,数据可以完成封装映射 如果字段和jav ...

  9. Oracle中的null与空字符串''的区别

    含义解释:问:什么是NULL?答:在我们不知道具体有什么数据的时候,也即未知,可以用NULL,我们称它为空,ORACLE中,含有空值的表列长度为零.ORACLE允许任何一种数据类型的字段为空,除了以下 ...

  10. Javaj基础知识runtime error

    遇到的java 运行时错误: NullPointerException空指针  ,简单地说就是调用了未经初始化的对象或者是不存在的对象,这个错误经常出现在创建图片,调用数组这些操作中,比如图片未经初始 ...