longest-consecutive-sequence Java code

来源:互联网 发布:随机梯度下降算法讲解 编辑:程序博客网 时间:2024/06/08 03:02

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.

import java.util.*;public class Solution {    public int longestConsecutive(int[] num) {        if(num == null||num.length == 0)            return 0;        Arrays.sort(num);        int count =1;        int max=1;        for(int i=1;i<num.length;i++)            {            if(num[i]==num[i-1]+1)                {                count++;                if(count>max)                    max=count;            }            else if(num[i]==num[i-1])                {                continue;            }            else                {                count=1;            }        }        return max;    }}
原创粉丝点击