笨蛋学算法之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);
    }
}
相关推荐
Zhou14113611 小时前
SpringMVC_02_注解开发实战
开发语言·windows·python
红姐跨境书11 小时前
AI 的底层逻辑:从数据、算法到智能的本质
人工智能·算法
繁华的地方不一定留下你的脚印11 小时前
C++ 算法与 ranges:用 find_if、transform 写清数据处理意图
开发语言·c++·算法
青山是哪个青山11 小时前
LeetCode 64:最小路径和
算法
blxr_11 小时前
力扣hot100寻找重复数https://leetcode.cn/problems/find-the-duplicate-number/
算法·leetcode·职场和发展
Json____11 小时前
基于 Spring Boot + Vue3 的在线考试管理系统实战
java·spring boot·后端·it学习·wwwoop.com
政企项目老覃11 小时前
金融医疗数据脱敏与隐私计算:从字段打码到联邦建模的落地复盘
程序人生·算法·金融·数据分析
weixin_5375904511 小时前
《Spring快速入门到精通》- 实例1.1
java·spring·intellij-idea
jason成都12 小时前
RTKLIB Java版:从C到Java的精密定位引擎,SPP/RTK/PPP/PPP-AR/PPP-RTK全栈实现
java·gnss·rtklib
Data_Journal12 小时前
如何在 Java 中使用 Selenium 绕过 CAPTCHA
java