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:
Sort words to at least O (nlgn) complexity. O (n) complexity, currently only found using hash to solve the scheme, add, remove, contains and other methods of the complexity is O (1), so two times the operation of the traversal is O (n).
Public classSolution { Public intLongestconsecutive (int[] num) { if(num==NULL|| Num.length==0) return0; HashSet<Integer> hs=NewHashset<integer>(); for(inti:num) {Hs.add (i); } intMax=1; for(inte:num) { intLeft=e-1; intRight=e+1; intTemp=1; while(Hs.contains (left)) {Hs.remove (left); In fact, it is equivalent to the NUM array to group, each element has been left only once temp++; Left--; } while(Hs.contains (right)) {Hs.remove (right); Ditto Right++; Temp++; } Max=Math.max (max, temp); } returnMax; }}
[Leetcode] longest consecutive Sequence