leetcode 128. Longest Consecutive Sequence
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int num: nums){
set.add(num);
}
int max_len=0;
for (int i=0; i<nums.length; i++){
int curr_num=nums[i];
int curr_max_len=1;
if (!set.contains(curr_num-1)){
//if the set already contains an element smaller than current one,
//we don't need to check this element since repetitive.
//we only want to check starting from the smallest element
while (set.contains(curr_num+1)){
curr_num+=1;
curr_max_len+=1;
}
max_len=Math.max(max_len, curr_max_len);
}
}
return max_len;
}
}