给一个未排序的序列,找出其中最长的连续序列的长度。
对于每个数都查找在数组中有没有x+1,x+2一直到最长。可以用一个hashset来存储数组中的数,这样可以很方便的判断有没有x+1…,但这样还是外层循环一次,内部循环o(n),因为当找到x到x+n是连续数组后,碰到x+1还要重新找一遍,则在外部遍历的时候,如果找到x-1存在,则从x开始就不可能是最长了,直接跳过。
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}