import java.util.HashSet;
import java.util.Set;
//用哈希表
//遍历哈希表中的元素,然后查看是否连续,然后更新最大长度
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> map = new HashSet<>();
//把nums元素加入hashmap中
for (int num : nums) map.add(num);
int result = 0;
for (int num : map) {
//如果不包含num - 1,那么当前元素就可以作为序列的起始位置计算长度
if (!map.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
//计算当前序列长度
while (map.contains(currentNum + 1)) {
currentNum += 1;
currentLength += 1;
}
result = Math.max(result, currentLength);
}
}
return result;
}
}
leetcode128. 最长连续序列
最新推荐文章于 2021-07-13 00:00:34 发布