题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.
Your algorithm should run in O(n) complexity.
大概意思:
求最长连续序列
要求 复杂度为O(n)
解题思路:
要求复杂度为0(n)这里可以使用哈希表 可以用HashMap 或者HashSet集合来解决
通过HashSet来将数组元素全部添加进来,然后遍历原数组,如果某数字在HashSet里面存在,那么将他删除,同时设置当前值的前后指针,通过删除前后指针来判断这个值的连续序列是多少,那么当前值的最大序列就是 前指针-后指针-1; 那为什么要删除这个值呢,因为如果遍历1的时候,那么同时也遍历了 2,3,4 ,那么当下一次遍历2的时候,又需要遍历1,3,4 这里面也浪费了大量时间
下面是代码:
public int longestConsecutive(int[] num) {
if(num == null || num.length ==0) {
return 0;
}
HashSet<Integer> set = new HashSet<Integer>();
int result = 0;
for(int i : num) {
set.add(i);
}
for(int i :num) {
while(set.remove(i)) {
int pre = i+1;
int rear = i-1;
while(set.remove(pre)) {
pre++;
}
while(set.remove(rear)) {
rear--;
}
result = Math.max(result, pre-rear-1);
}
}
return result;
}