Longest consecutive sequence length
Java
Hard
4 views
Problem Description
Task: return length of the longest consecutive sequence (order in array does not matter). Use HashSet.
Output Format
Return value
Constraints
Expected O(n) average.
Official Solution
static int longestConsecutive(int[] a){java.util.HashSet<Integer> set=new java.util.HashSet<>();for(int x:a) set.add(x);int best=0;for(int x:set){if(!set.contains(x-1)){int cur=x,len=1;while(set.contains(cur+1)){cur++;len++;}if(len>best) best=len;}}return best;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!