128. Longest Consecutive Sequence
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.
此题有三种解法,第一种是用hashmap来做,遍历一次数组元素,遍历到数组某一值时,将该值赋予与他相连的其他元素+1值,即为元素个数,代码如下:
public class Solution {
public int longestConsecutive(int[] nums) {
int res = 0;
Map<Integer,Integer> map = new HashMap<>();
for(int n:nums){
if(!map.containsKey(n)){
int left = map.getOrDefault(n-1,0);
int right = map.getOrDefault(n+1,0);
int sum = left+right+1;
map.put(n,sum);
res = Math.max(res,sum);
map.put(n-left,sum);
map.put(n+right,sum);
}
}
return res;
}
}
第二种做法是使用hashset来做,一次性把数组元素全部放在set里面,然后遍历数组或者set,遍历到某一值时候,检查是否有该值-1,即检查最小值,然后找到最大值,做差就是长度,代码如下:
public class Solution {
public int longestConsecutive(int[] nums) {
int res=0;
Set<Integer> set = new HashSet<Integer>();
for(int i:nums){
set.add(i);
}
for(int n:nums){
if(!set.contains(n-1)){
int m = n+1;
while(set.contains(m)){
m++;
}
res = Math.max(res,m-n);
}
}
return res;
}
}