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.
Solution:
1 Public classSolution {2 Public intLongestconsecutive (int[] num) {3 4Set<integer> set =NewHashset<integer>();5 for(inti=0;i<num.length;i++) Set.add (Num[i]); 6 intMaxLen = 0;7 intindex = 0;8 while(index<num.length) {9 if(!Set.contains (Num[index])) {Tenindex++; One Continue; A } - - intLen =0; the intval =Num[index]; - while(Set.contains (val)) { - Set.remove (val); -len++; +val--; - } +val = num[index]+1; A while(Set.contains (val)) { at Set.remove (val); -len++; -val++; - } - if(Maxlen<len) maxlen=Len; -index++; in } - to + returnMaxLen; - the } * $}
Leetcode-longest consecutive Sequence