[Java] HashSet Solution

programming
Tags: #<Tag:0x00007f1828028e28>

#1
public class Solution {
    // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
    public int longestConsecutive(final int[] A) {
        HashSet<Integer> seen = new HashSet<>();
        for(int x : A){
            seen.add(x);
        }
        int maxx = 0;
        for(int x : seen){
            if(!seen.contains(x-1)){
                int maxNum = x;
                int maxLen = 1;
                while(seen.contains(maxNum+1)){
                    maxNum += 1;
                    maxLen += 1;
                }
                maxx = Math.max(maxx, maxLen);
            }
        }
        return maxx;
    }
}