141. 环形链表
时间:2021-08-29
本文章向大家介绍141. 环形链表,主要包括141. 环形链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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?
环形链表。
用快慢指针法:
慢:一次走一步
快:一次走两步
如果快指针走到null则无环
if(f.next==null || f.next.next==null){ return false; }
如果快慢相遇则有环
public class Solution { public boolean hasCycle(ListNode head) { if(head==null||head.next==null||head.next.next==null){ return false; } ListNode s=head; ListNode f=head.next.next; while(s!=f){ if(f.next==null || f.next.next==null){ return false; } s=s.next; f=f.next.next; } return true; } }
用HashSet
把当前处理的链表加入到Set中,如有环,必会找到已存在的链表
api:
add
contains
public class Solution { public boolean hasCycle(ListNode head) { if(head==null||head.next==null||head.next.next==null){ return false; } HashSet<ListNode> hashSet = new HashSet<>(); ListNode cur=head; while (cur!=null){ if(hashSet.contains(cur)){ return true; } hashSet.add(cur); cur=cur.next; } return false; } }
原文地址:https://www.cnblogs.com/iwyc/p/15202290.html
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Java自动化测试(特殊元素处理 25)
- 那些Vue开发遇到的坑---响应式系统
- 基于Ansible和Devops的一键测试环境部署实践
- STM32硬核DIY机械键盘|蓝牙USB双模|灯控
- R语言隐马尔可夫模型HMM识别不断变化的股票市场条件
- 看完这篇并发后,又能扯皮了?
- Twitter美国航空公司情绪数据集的监督或半监督ULMFit模型
- 一文帮你理解整个 SRE 运维体系!
- 拆解式解读如何用飞桨复现胶囊神经网络(Capsule Network)
- 我用飞桨Parakeet合成小姐姐声音帮我“读”论文
- 【5分钟玩转Lighthouse】搭建WordPress博客
- vue接入腾讯地图(一)【点击事件】
- Redis文件事件&时间事件处理机制
- Redis持久化策略
- Redis二进制安全的原理