题目描述
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
示例
题解
利用HashSet进行去重。
寻找起点连续序列的起点(如果起点数字为a,那么HashSet中必不包含a - 1),依次计算各个起点的连续序列长度,得出最大值。
代码
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> hash = new HashSet<>();
// 存入HashSet
Arrays.stream(nums).forEach(
hash::add
);
int max = 0;
int sum = 0;
for (int thisNum : nums) {
// 寻找起点,如果set中存在比当前数字小1的数字,则不是起点,需要继续寻找
if (hash.contains(thisNum - 1)) {
continue;
}
// 已经找到起点
else {
// 计算当前起点的最大长度,并与现有最大值进行比较
while (hash.contains(thisNum)) {
sum++;
thisNum++;
}
if (sum > max) {
max = sum;
}
sum = 0;
}
}
return max;
}
}