1- 思路
哈希表
- 1- 哈希表
- 利用
HashSet
充当哈希表,快速判断是否有元素在
- 2- 遍历数组
- 2.1 存入 HashSet:将所有结果存入到
HashSet
中 - 2.2 实现遍历逻辑
- 2.3 定义 nowNum 和 nowLength:
- 如果当前
num
不存在前一个连续值,更新 nowNum
和 nowLength
- 如果当前 num 存在后一个连续值,更新
nowNum+=1
和 nowLength+=1
- **2.4 每次遍历更新 **
res
2- 实现
⭐128. 最长连续序列——题解思路
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/7d668a6cd4904f5c8600e5af8809fd2c.png)
class Solution {
public int longestConsecutive(int[] nums) {
HashSet<Integer> hs = new HashSet<>();
int res = 0;
for(int n:nums){
hs.add(n);
}
for(int num:nums){
if(!hs.contains(num-1)){
int nowNum = num ;
int nowLength = 1 ;
while(hs.contains(nowNum+1)){
nowNum++;
nowLength++;
}
res = Math.max(res,nowLength);
}
}
return res;
}
}
3- ACM 实现
public class longestSub {
public static int longestS(int[] nums){
HashSet<Integer> hs = new HashSet<>();
int res = 0;
for(int i : nums){
hs.add(i);
}
for(int num:nums){
if(!hs.contains(num-1)){
int nowNum = num;
int nowLen = 1;
while(hs.contains(nowNum+1)){
nowLen++;
nowNum++;
}
res = Math.max(res,nowLen);
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数组长度");
int n = sc.nextInt();
int[] nums = new int[n];
for(int i = 0 ; i < n;i++){
nums[i] = sc.nextInt();
}
System.out.println("结果是"+longestS(nums));
}
}