当前位置:网站首页>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
总结
判断链表是否有环使用快慢指针
边栏推荐
- How to install mysql8.0 database under Windows system? (Graphic tutorial)
- Application and Optimization Practice of 100 million level monthly live national karaoke feed service in Tencent cloud mongodb
- leetcode刷题:字符串06(实现 strStr())
- Usage of MGrid in numpy
- Listing of maolaiguang discipline on the Innovation Board: it is planned to raise 400million yuan. Fanyi and fanhao brothers are the actual controllers
- 花店橱窗布置【动态规划】
- How to create an OData service with the graphical modeler on the sap BTP platform
- YuMinHong: New Oriental does not have a reversal of falling and turning over, destroying and rising again
- Final part of web crawler: send directional messages to 100000 Netease cloud users
- Introduction to dependency injection in SAP Spartacus
猜你喜欢

Leetcode: hash table 08 (sum of four numbers)

协同过滤进化版本NeuralCF及tensorflow2实现

网络爬虫2:抓取网易云音乐评论用户ID及主页地址

Simple Lianliankan games based on QT

Leetcode(452)——用最少数量的箭引爆气球

网易云信正式加入中国医学装备协会智慧医院分会,为全国智慧医院建设加速...

关于appium踩坑 :Encountered internal error running command: Error: Cannot verify the signature of (已解决)

About appium trample pit: encountered internal error running command: error: cannot verify the signature of (solved)

财务费用分析怎么分析

Leetcode: String 04 (reverse the words in the string)
随机推荐
Establish a connection with MySQL
基于启发式搜索的一字棋
与 MySQL 建立连接
Is there any risk in registering and opening an account for stock speculation? Is it safe?
numpy中mgrid的用法
Sword finger offer 12 Path in matrix
leetcode刷题:字符串05(剑指 Offer 58 - II. 左旋转字符串)
Leetcode(763)——划分字母区间
Installation avec homebrew dans un environnement Mac OS [email protected]
诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
The latest 2022 research review of "continuous learning, CL"
不要做巨嬰了
YuMinHong: New Oriental does not have a reversal of falling and turning over, destroying and rising again
VB.net类库(进阶版——1)
Leetcode(452)——用最少数量的箭引爆气球
模块五作业
矩阵求导及其链式法则
Which securities company is the most convenient, safe and reliable for opening an account
QT based "synthetic watermelon" game