给定一个无序的整数类型数组,求最长的连续元素序列的长度。 例如: 给出的数组为[100, 4, 200, 1, 3, 2], 最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4 你需要给出时间复杂度在O(n)之内的算法

import java.util.*;
public class Solution {
    public int longestConsecutive(int[] num) {
        if( num==null || num.length == 0){
            return 0;
        }
        if(num.length==1){
            return 1;
        }
        Arrays.sort(num);
        int [] count = new int[num.length];
        int j = 0;
        int sum = 1;
        for(int i = 0; i < num.length-1; i++){
            if(num[i]+1 == num[i+1]){
                sum+=1;
               count[j++] = sum;
            }else if(num[i] == num[i+1]){

                count[j++] = sum;
            }
            else{
                count[j++] = 1;
                sum=1;
            }
        }
        Arrays.sort(count);
        return count[count.length-1];
    }
}

 

posted @ 2019-08-19 09:50  紫色的雪  阅读(1170)  评论(0编辑  收藏  举报