问题描述
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
[1, 2, 3, 4]。它的长度为 4。
代码实现
思路:用一个字典存储中间值遍历数组,对于数字I,找到的i-1和i + 1的对应的值值,如果不存在则记为0。然后把我的值值设为I-1,I + 1个的值值之和,并加1,相当于连接起来。同时置最左端和最右端的数的值值为我的值值(中间的数都已经出现过,不会再用到了)。然后更新一次最大值。
代码如下:
public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] num) {
// write you code here
if(num.length <= 1)
return num.length;
Set<Integer> set = new HashSet<Integer>();
for(int e:num)
set.add(e);
int max = 1;
for(int e:num){
int count = 1;
int left = e - 1;
int right = e + 1;
while(set.contains(left)){
count++;
set.remove(left);
left--;
}
while(set.contains(right)){
count++;
set.remove(right);
right++;
}
max = Math.max(max,count);
}
return max;
}
}
1242

被折叠的 条评论
为什么被折叠?



