1.题目
给定一个未排序的整数数组,找出最长连续序列的长度。
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
2.算法
由于这道题需要算法复杂度为O(n),而很多排序算法复杂度为nlog(n),所以不适合用排序算法,而用hash来解决的方案,add, remove, contains 等方法的复杂度都是 O(1),所以可以用hashset来解决,这道题分两步解
1.把数组中的数放到hashset中,便于查找,
2,找到最大连续整数,我们可以任意选一个数,向两边找,找到就把他从表中删去
public int longestConsecutive(int[] num)
{
// write you code here
if (num == null || num.length == 0)
{
return 0;
}
HashSet<Integer> set = new HashSet<Integer>();
int res = 1;
for (int i = 0; i < num.length; i++)
{
set.add(num[i]);
}
while (!set.isEmpty())
{
Iterator<Integer> it = set.iterator();
int item = (int)it.next();
set.remove(item);
int len = 1;
int i = item - 1;
while (set.contains(i))
{
set.remove(i--);
len++;
}
i = item + 1;
while (set.contains(i))
{
set.remove(i++);
len++;
}
if (len > res)
{
res = len;
}
}
return res;
}