笨蛋学算法之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);
    }
}
相关推荐
xiaoqiMikko2 分钟前
你升的是 jackson-databind,中招的是 jackson-core:一个超长 JSON key 就能吃掉 200MB 堆
java·安全
Lazionr5 分钟前
多态:从多种形态到运行时绑定
开发语言·c++
不正经的码狗6 分钟前
Eclipse汉化(快速,推荐)
java·eclipse
极客互动API8 分钟前
极客互动-企业微信基于外部API接口实现AI客服自动接管外部联系人消息收发
java·微信·企业微信·ai编程·rpa
Sam_Deep_Thinking9 分钟前
关于java final关键字的可见性
java·后端·面试·程序员
tryxr11 分钟前
矩阵的几种基础变换
java·数据结构·算法·矩阵
写后端的胖头鱼12 分钟前
如何区分IO/CPU 密集型,线程池核心参数怎么设置
java·线程池·多线程·io密集·cpu密集
mmmmath_315 分钟前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
大黄说说22 分钟前
iOS 列表滑动卡顿:UITableView / UICollectionView 深度优化实战
开发语言
Selvaggia26 分钟前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法