import java.util.HashSet;
/**
* Longest Consecutive Sequence
*
* 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.
*/
public class LongestConsecutiveSequence {
public static int getConsecutiveSequence(int[] arr) {
if(null == arr || arr.length==0) {
return 0;
}
HashSet<Integer> set = new HashSet<Integer>();
for(int i : arr) {
set.add(i);
}
int longest = 1;
for(int i : arr) {
if(!set.contains(i)){
continue;
}
int length = 1;
for(int j=i-1; set.contains(j); length++, j--){
System.out.println(j);
set.remove(j);
}
for(int j=i+1; set.contains(j); length++, j++){
set.remove(j);
}
longest = Math.max(longest, length);
}
return longest;
}
public static void main(String[] arrs){
int[] arr = {100, 4, 200, 1, 3, 2};
int result = getConsecutiveSequence(arr);
System.out.print(result);
}
}