public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
if(num.length == 0) return 0;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < num.length; i++) {
set.add(num[i]);
}
int result = 0;
for(int i = 0; i < num.length; i++) {
if(set.contains(num[i])) {
result = Math.max(result, getLength(set, num[i], false) + getLength(set, num[i] + 1, true));
}
}
return result;
}
public int getLength(Set<Integer> set, int i, boolean flag) {
int result = 0;
while(set.contains(i)) {
result++;
set.remove(i);
if(flag == false) i--;
else i++;
}
return result;
}
Longest Consecutive Sequence
最新推荐文章于 2021-03-25 11:39:43 发布