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.

 

 

要求时间复杂度为O(n)。本人使用了HashMap来进行的,不断维护新加节点所能构成序列的左边界和右边界,

import java.util.HashMap;
public class Solution {
public int longestConsecutive(int[] nums) {
// 判断异常
if(nums == null || nums.length == 0) {
return 0;
}
// 全局变量max来维护最大值
int max = 1;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
// 从头到尾遍历所有的数组元素
for(int i = 0; i < nums.length; i++) {
while(!map.containsKey(nums[i])) {
map.put(nums[i],1);
if(map.containsKey(nums[i] - 1)) {
max = Math.max(max, merge(map, nums[i] - 1, nums[i]));
}
if(map.containsKey(nums[i] + 1)) {
max = Math.max(max, merge(map, nums[i], nums[i] + 1));
}
}
}
return max;
}
// 创建维护方法,维护左右边界
public int merge(HashMap<Integer,Integer> map, int small, int big) {
// 找出左边界
int left = small - map.get(small) + 1;
// 找出右边界
int right = big + map.get(big) - 1;
// 确定左右边界的长度
int len = right - left + 1;
// 只对左右边界进行维护即可
map.put(left, len);
map.put(right, len);
// 返回相应的长度
return len;
}
}