给定一个未排序的整数数组,找出最长连续序列的长度。
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
说明
要求你的算法复杂度为O(n)
解题思路:
由于算法复杂度要求,可以使用空间换时间。将所有数字都存入HashSet中,再遍历数组,从遍历的元素向两边扩展搜索,看看有无连续序列。
public class Solution {
/**
* @param num: A list of integers
* @return: An integer
*/
public int longestConsecutive(int[] num) {
// write your code here
Set<Integer> set = new HashSet<>();
for(int i=0; i<num.length; i++)
set.add(num[i]);
int res = 0;
for(int i=0; i<num.length; i++){
int tmp1 = num[i] - 1;
int l = 0; //记录其左边有多少连续数
while(set.contains(tmp1)){
set.remove(tmp1);
l++;
tmp1--;
}
int tmp2 = num[i] + 1;
int r = 0; //记录其右边有多少连续数
while(set.contains(tmp2)){
set.remove(tmp2);
r++;
tmp2++;
}
res = Math.max(res, l + r + 1);
}
return res;
}
}
二刷,注意需要遍历的时候删除元素,这样才能避免很多无谓的重复,时间复杂度才是O(n)
public class Solution {
/**
* @param num: A list of integers
* @return: An integer
*/
public int longestConsecutive(int[] num) {
// write your code here
Set<Integer> set = new HashSet<>();
for(int i : num)
set.add(i);
int res = 1;
for(int i : num){
int temp = 1;
for(int j=i-1; set.contains(j); j--){
set.remove(j);
temp++;
}
for(int j=i+1; set.contains(j); j++){
set.remove(j);
temp++;
}
res = Math.max(res, temp);
}
return res;
}
}