最长连续数组

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88235434

24、最长连续数组
longest-consecutive-sequence:Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.
Your algorithm should run in O(n) complexity.
题设要求:给定未排序的整数数组,找到最长连续元素序列的长度。
例如,给定数组[100,4,2,1,3,2],则最长的连续元素序列是[1,2,3,4]。 返回长度:4。
注意:算法应该以O(n)复杂度运行。
代码:

import java.util.*;
public class Solution {
    public int longestConsecutive(int[] num) {
        int len = num.length;
        //长度为1/0,单个元素默认为最长连续
        if(len<=1){
            return len;
        }
        //对数组进行排序
        Arrays.sort(num);
         
        //定义newlen存放新数组(最长连续数组)长度
        int newlen = 0;
        //定义当前连续数组长度
        int cur = 1;  
        for(int i=1;i<len;i++){
            if(num[i]==num[i-1]){//相等的话,返回for循环
                continue;
            }
            if(num[i]-num[i-1]==1){//连续的情况
                cur++;
            }else{
                if(cur>newlen){
                    newlen = cur;
                }
                cur = 1;  //重新开始寻找连续数组
            }
        }
        if(cur>newlen){
            newlen = cur;
        }
        return newlen;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88235434