当前位置:   article > 正文

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

笨蛋学算法之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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/726701
推荐阅读
相关标签
  

闽ICP备14008679号