给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
解题思路:要求时间复杂度为O(n),第一时间想到哈希,遍历数组的同时保存当前元素所在的最长连续序列长度,取其中最大值。遍历时出现以下几种情况
情况1:该元素已存在,则跳过
情况2:存在左连续序列,长度为1+left,更新序列首元素长度
情况3:存在右连续序列,长度为1+rignt,更新序列尾元素长度
情况4:同时存在左右连续序列,长度为1+left+right,更新序列首尾长度
自己先写了一遍,然后看到一段使用哈希getOrDefault()方法写的代码,很优美,果断重写(这里为了更具可读性,没有直接使用getOrDefault()方法)
public int longestConsecutive(int[] nums) {
int max = 0;
HashMap<Integer,Integer> hash = new HashMap<>();
for(int i = 0;i < nums.length;i++) {
if(!hash.containsKey(nums[i])) {
int left = findConsecutive(hash,nums[i] - 1);
int right = findConsecutive(hash,nums[i] + 1);
hash.put(nums[i], 1 + left + right);
if (left != 0)
hash.replace(nums[i] - left, 1 + left + right);
if (right != 0)
hash.replace(nums[i] + right, 1 + left + right);
max = Math.max(max,1 + left + right);
}
}
return max;
}
public int findConsecutive(HashMap hash, int key){
if(hash.containsKey(key))
return (int)hash.get(key);
else
return 0;
}