笨蛋学算法之LeetCodeHot100_3_最长连续序列(Java)

java 复制代码
package com.lsy.leetcodehot100;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class _Hot3_最长连续序列 {
    public static int longestConsecutive(int[] nums) {

        //创建set去重
        //对重复的数字进行去重
        Set<Integer> set = new HashSet<>();
        //将数字存入set
        for(int num:nums){
            set.add(num);
        }

        //记录当前遍历的序列的最长长度
        int max = 0;
        for (int num : set) {
            //记录当前的遍历的数字序列最后一个元素
            int current = num;

            //检查current是否是起始数字,如果在的话说明不是,如果不在说明是
            if(!set.contains(current-1)){
                //如果不在,就继续遍历元素,看后面还有没有连续的数字
                while(set.contains(current+1)){
                    //有就自增记录当前的元素
                    current++;
                }
            }

            //如果 num 是 5 而 cur 是 8,那么这个序列是 [5, 6, 7, 8],长度为 8 - 5 + 1 = 4
            //如果重新计算的序列长度大于当前的max,就更新max的长度为最长长度
            max = Math.max(max,current-num+1);
        }
        return max;
    }

    public static void main(String[] args) {
        int[] nums= {1,3,2,0,5,6,9,8,7,3,0,3,5};

        int max = longestConsecutive(nums);
        System.out.println(max);
    }
}
相关推荐
孙启超24 分钟前
【AI开发之Rust】第 22 课:一键多平台与工程收尾 —— CI、发布检查与结课
开发语言·后端·rust
xcl09255 小时前
北京24小时自助健身房系统软件开发实战:从架构到部署全流程指南
java·spring boot·架构
一 乐7 小时前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
卓怡学长7 小时前
w214基于jsp知道特产网
java·intellij-idea
步行cgn7 小时前
Spring 注解使用详解
java·spring
一条小小yu7 小时前
Spring IoC的理解
java·后端·spring
longlongzihan8 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
落魄实习生8 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
封印师请假去地球钓鱼8 小时前
边解边变的问题:从“决策依赖“一词出发
人工智能·算法
旺仔学长 哈哈8 小时前
springboot钓鱼爱好者交流平台APP设计与实现
java·spring boot·mysql·充电桩管理系统