当前位置:网站首页>leetcode:141. 环形链表【哈希表 + 快慢指针】
leetcode:141. 环形链表【哈希表 + 快慢指针】
2022-06-26 21:38:00 【白速龙王的回眸】

分析
如果用哈希表看内存位置也是可以的
但是如果要更小的内存空间的话,可以使用快慢指针
floyd判圈:如果有环,快慢指针必定相遇
算法判断:
如果head或者head.next不存在就必定没有环
然后slow从head开始,fast从head.next开始
一直看看slow和fast相等与否,用while循环,一旦相等就肯定有环
在while循环内,如果没有fast或者没有fast.next就肯定没有环了
然后slow走一步,fast走两步
ac code
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
# start
slow, fast = head, head.next
# if have cycle, slow and fast must meet
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
总结
判断链表是否有环使用快慢指针
边栏推荐
- 「连续学习Continual learning, CL」最新2022研究综述
- 茂莱光学科创板上市:拟募资4亿 范一与范浩兄弟为实控人
- 12个MySQL慢查询的原因分析
- curl: (35) LibreSSL SSL_ connect: SSL_ ERROR_ SYSCALL in connection
- C: Reverse linked list
- 剑指 Offer II 098. 路径的数目 / 剑指 Offer II 099. 最小路径之和
- Convolutional neural network (CNN) explanation and tensorflow2 code implementation
- MacOS環境下使用HomeBrew安裝[email protected]
- 记录一次Redis大Key的排查
- Sword finger offer II 098 Number of paths / Sword finger offer II 099 Sum of minimum paths
猜你喜欢

Establish a connection with MySQL

【protobuf 】protobuf 升级后带来的一些坑

花店橱窗布置【动态规划】

leetcode刷题:字符串01(反转字符串)

Netease Yunxin officially joined the smart hospital branch of China Medical Equipment Association to accelerate the construction of smart hospitals across the country

Leetcode question brushing: String 05 (Sword finger offer 58 - ii. left rotation string)

The latest 2022 research review of "continuous learning, CL"

Implementation of collaborative filtering evolution version neuralcf and tensorflow2

Dynamic parameter association using postman

基于SSH框架的学生信息管理系统
随机推荐
QT based "synthetic watermelon" game
VB.net类库(进阶——2 重载)
12个MySQL慢查询的原因分析
经典Wide & Deep模型介绍及tensorflow 2代码实现
Leetcode question brushing: String 02 (reverse string II)
十大券商注册开户有没有什么风险?安全吗?
y48.第三章 Kubernetes从入门到精通 -- Pod的状态和探针(二一)
【 protobuf 】 quelques puits causés par la mise à niveau de protobuf
Final part of web crawler: send directional messages to 100000 Netease cloud users
What are the accounting elements
Which securities company is the most convenient, safe and reliable for opening an account
Shiniman household sprint A shares: annual revenue of nearly 1.2 billion red star Macalline and incredibly home are shareholders
leetcode刷题:字符串06(实现 strStr())
不要做巨嬰了
第2章 构建自定义语料库
DAST black box vulnerability scanner part 5: vulnerability scanning engine and service capability
360 mobile assistant is the first to access the app signature service system to help distribute privacy and security
Leetcode(122)——买卖股票的最佳时机 II
How to enable Hana cloud service on SAP BTP platform
Establish a connection with MySQL