JAVA O(N) solution using Set. The editorial solution seems better though


#1

I had to use a bad looking ForEach loop in order to get an element from the set. Please suggest a better approach for getting an element from the set.
Here is the code:

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public int longestConsecutive(final List A) {
int n=A.size();
int min=Integer.MAX_VALUE;
Set pres=new HashSet<>();
for(int i=0;i<n;i++){
int val=A.get(i);
if(val<min){
min=val;
}
pres.add(val);
}
int len=1;
int cur=min;
while(pres.size()>0){
pres.remove(cur);
int low=cur;
int high=cur;
int llen=1;
while(pres.contains(–low)){
pres.remove(low);
llen++;
}
while(pres.contains(++high)){
pres.remove(high);
llen++;
}
if(llen>len){
len=llen;
}
for(Integer i:pres){
cur=i;
break;
}
}
return len;
}
}