【d54_2】【Java】【力扣】142.环形链表

思路

关于判断是否重复的就hashSet,这种有主动去重性质的类

新建一个hashSet

遍历链表并放进hashSet,

如果不能放,说明这个遍历过,这个就是环的地方

如果最后到遍历到null,说明没环

代码

复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
         //都加入hashset,listNode是地址引用,节点一定唯一
            //如果有不能添加的,返回当前节点
            HashSet<Object> set = new HashSet<>();
            ListNode cur = head;
            while (cur != null) {
                //如果能添加,continue
                if(!set.add(cur)){
                 return cur;   
                }
                 cur = cur.next;
            }
            //等于null,退出,所以没有环,返回null
            return null;
    }
}

记录

总结

关于判断是否重复的就hashSet,这种有主动去重性质的类

相关推荐
EatFan3 小时前
Spring Boot 4.0 升级清单:JDK 基线、Jakarta 命名空间、Observation API 与第三方组件兼容一次讲清
java·spring boot·后端
辰海Coding3 小时前
平台如何接入一台物联网设备?又该如何设计它的通信协议?
java·物联网
代码民工正电荷3 小时前
JAVA重要知识点和集合
java·开发语言
李少兄5 小时前
IDEA Apifox Helper 插件踩坑:2.0.15-243 版本“导出指定接口”参数描述丢失问题解析与修复方案
java·ide·intellij-idea
努力攀登的小k5 小时前
《新手练表:从建表到删表全操作|从零学会表操作》
java·数据库·mysql
Yetian_20006 小时前
Postman测试上传图片文件接口
java·postman
爪哇碎碎念6 小时前
【Java】从一次 cache.get(key) 进去:缓存击穿一瞬间打出 200 次 DB,JDK 17 实测三种解法
java·redis·缓存
csdn_aspnet6 小时前
Java 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
java·算法
源码_空间7 小时前
基于Springboot的在线编程练习判题平台(源码+文档)
java·spring boot·后端
小手cool8 小时前
二分查找:在有序数组中查找最接近 target 的元素索引
java·数据结构·算法