笨蛋学算法之LeetCodeHot100_3_最长连续序列(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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值