我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/description/
题目描述:
知识点:Map集合的应用,数组
思路:用一个Map集合记录数组中的值是否已被计算过
初始时,Map对应的键集合中包含数组中的所有值,均未被计算过,每个键对应的布尔值为false。
对nums数组中的每一个元素,左指针left取为nums[i] - 1,右指针right取为nums[i] + 1左右依次扩展,每次向左扩展间隔为1,向右扩展间隔也为1,如果发现其左或右边的值在Map对应的键集合中,且未被计算过,且在整数范围内,就令左指针减1或右指针加1,最后right - left - 1即为当前数字nums[i]所对应的最长连续序列长度。
时间复杂度和空间复杂度均为O(n),其中n为nums数组的大小。
JAVA代码:
public class Solution {
public int longestConsecutive(int[] nums) {
int result = 0;
HashMap<Integer, Boolean> calculatedMap = new HashMap<>();
for(int i = 0; i < nums.length; i++){
calculatedMap.put(nums[i], false); //初始时刻所有数均未被考虑过
}
for(int i = 0; i < nums.length; i++){
if(calculatedMap.get(nums[i])){ //如果nums[i]已经被考虑过了,跳过本次循环
continue;
}
int left = nums[i] - 1;
while(calculatedMap.containsKey(left) && !calculatedMap.get(left) && left >= Integer.MIN_VALUE){
calculatedMap.put(left, true);
left--;
}
int right = nums[i] + 1;
while(calculatedMap.containsKey(right) && !calculatedMap.get(right) && right <= Integer.MAX_VALUE){
calculatedMap.put(right, true);
right++;
}
result = Math.max(result, right - left - 1);
}
return result;
}
}
LeetCode解题报告: