题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked
哈希
先使用哈希表HashSet去重,然后遍历哈希表,如果有比当前元素小1的存在,则跳过,如果没有,就开始匹配,看最长能匹配到多少
class Solution {
public int longestConsecutive(int[] nums) {
//使用HashSet去重
Set<Integer> set = new HashSet<Integer>();
//哈希表存储数据
for(int num : nums){
set.add(num);
}
//存储答案
int cnt = 0;
//遍历哈希表
for(int num : set){
//如果不存比当前数小1的,那就继续执行,否则就跳过
if(!set.contains(num - 1)){
//当前数
int curnum = num;
//当前长度
int curcnt = 1;
//循环判断,如果存在比当前数大1的,就继续执行
while(set.contains(curnum + 1)){
//当前数加1
curnum++;
//当前长度加1
curcnt++;
}
//取最长的长度
cnt = Math.max(cnt, curcnt);
}
}
return cnt;
}
}
还剩97题!