```
public int longestConsecutive(int[] num) {
HashSet<Integer> hs = new HashSet<Integer>();
for(int i:num)
hs.add(i);
int maxlen=0;
for(int i:num)
{
if(!hs.contains(i))
continue;
int len =1;
hs.remove(i);
int smaller = i-1;
while(hs.contains(smaller))
{
len++;
hs.remove(smaller);
smaller--;
}
int bigger = i+1;
while(hs.contains(bigger))
{
len++;
hs.remove(bigger);
bigger++;
}
if(len>maxlen)
maxlen = len;
}
return maxlen;
}
```