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.
首先最native的方法就是用一个数组记录数c是否出现,然后再从左到右遍历,看看连续最长的序列是多长。但这么做一个是空间复杂度太高,而且遇到负数不好处理。。
我们大可不必用这么大的数组来记录已经遍历的信息。
我们用一个lmap和一个rmap记录,map中的key是数组中的数,value是记录最长向右(左)能延伸的距离。
然后我们需要考虑下面几种情况。
比如已经遍历了 [ 1, 2,4,5 ,8,9,10]
1 ,数已经出现,比如下一个数字是2,则continue,跳过。
2 数c未出现,数c+1出现,数c-1没出现,比如下一个数字是7,因为7+1=8出现了,
那么需要执行两个操作:
(1)c可以向右扩展rmap[c+1]+1个长度
也就是把rmap[7]设为rmap[8]+1 ,
(2)c的最右边的数,可以向左扩展rmap[c+1]+1个长度
而把7向右走到头的最后一个数(也就是10)的lmap设为7的rmap的值。也就是执行lmap[10]= rmap[7]
3 数c未出现,数c-1出现,数c+1没出现 同上,就是变个方向
4 数c未出现,数c-1出现,数c+1出现,只需要把c-1向左走到头的数的rmap,和c+1向右走到头的数的lmap更新成。rmap[c+1]+lmap[c-1]+1
比如下一个数是3,就可以吧rmap[1]设为5,把lmap[5]设为5.
最后找lmap或rmap中最大的值即可。
public int longestConsecutive(int[] nums) {
HashMap<Integer,Integer> lmap = new HashMap<>();
HashMap<Integer,Integer> rmap = new HashMap<>();
for(int c :nums){
if(lmap.containsKey(c)) {
continue;
}
lmap.put(c, 1);
rmap.put(c, 1);
if(lmap.containsKey(c-1)&&rmap.containsKey(c+1)){
int r = rmap.get(c+1);
int l = lmap.get(c-1);
lmap.put(c+r,l+r+1);
rmap.put(c-l,l+r+1);
}else {
if (lmap.containsKey(c - 1)) {
int l = lmap.get(c-1);
lmap.put(c, l+1);
rmap.put(c-l,l+1);
}
if (rmap.containsKey(c + 1)) {
int r = rmap.get(c+1);
rmap.put(c, r+1);
lmap.put(c+r,r+1);
}
}
}
int max = 0;
for (Map.Entry<Integer,Integer> entry:lmap.entrySet()){
max = Math.max(max,entry.getValue());
}
return max;
}