longest consecutive sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class  {
public int longestConsecutive(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
int res=0;
for(int n:nums)
{
if(!map.containsKey(n))
{
int left=map.containsKey(n-1)? map.get(n-1): 0;
int right=map.containsKey(n+1)? map.get(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;
}
}

思路:
1.我们这边需要保证连续的数字无论是哪一个,map取值都是连续的个数。
2.遇到相同的数字不予处理。