【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,这种有主动去重性质的类

相关推荐
o盟9 分钟前
maven本地仓库有 总是去私仓中下载
java·maven·intellij-idea
devpotato16 分钟前
Java 批量并发请求:从“能并发“到“结果按完成顺序可用“的三种写法与选型
java
Navigator_Z21 分钟前
LeetCode //C++ - 1226. The Dining Philosophers
c语言·算法·leetcode
苏生Susheng1 小时前
【软件实施】Linux企业运维常用命令手册
java·linux·运维·服务器·springboot·springcloud·软件实施
想要成为老金高手1 小时前
Kubernetes 调度器详解:从 nodeName 到污点容忍
java·容器·kubernetes
吴长建先生重名了1 小时前
ElasticSearch 检索系统性能优化实战:基准测试
java
西索斯coding1 小时前
doubao-seed-2.1-turbo 调用一直 401 怎么办?pro 版同样的 Key 却正常——5 分钟排查定位指南
java·服务器·数据库·ai
旧梦95271 小时前
Java SortedMap 接口详解:从入门到实战
java·开发语言
莫陌尛.1 小时前
Java_this构造方法
java·开发语言
2601_962297252 小时前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比