public int longestConsecutive(int[] num) {
Set<Integer> set = new HashSet<Integer> ();
for (int i:num) set.add(i);
int max = 0;
for (int i=0; i<num.length; i++) {
if (set.contains(num[i])) {
int next = num[i]-1;
int count = 1;
set.remove(num[i]);
while (set.contains(next)) {
set.remove(next);
next--;
count++;
}
next = num[i]+1;
while (set.contains(next)) {
set.remove(next);
next++;
count++;
}
max = Math.max(max, count);
}
}
return max;
}
}
没有评论:
发表评论