```
public int longestConsecutive(int[] nums) {
Arrays.sort(nums);
int j = 0;
int max = 0;
int offset = 0;
for(int i =0;i<nums.length;i++){
if(i!=0&&nums[i]==nums[i-1]){
offset++; // record number of duplicates
}
if(i-j -offset == nums[i] - nums[j]){
max = Math.max(max,i-j+1-offset);
}else{
j = i;
offset = 0;
}
}
return max;
}
```