题目: 给你一个数组 nums
,求出其中的最长连续序列。比如输入为[1,2,3,5,6,9],输出为[1,2,3]
思想: 将数组中的元素存入Set
集合中:
-
若
Set
中不包含num - 1
这个值,则说明该值是一个可能结果值的起点(比如1和5)-
从这个值开始,若
Set
中包含currNum + 1
,则说明这是一个连续序列 -
判断这一个序列长度是否是最大的,更改最长序列长度,最终将该值存储下来
-
**总结:**先找到连续序列的起点,然后根据起点与集合元素找到该序列的其他值
代码:
java
public class test{
public static int[] longestSub(int[] nums){
//数组为空,直接返回
if(nums == null || nums.length == 0){
return new int[0];
}
//创建一个Set集合存储数组的每个值
Set<Integer> set = new HashSet<>();
for(int num : nums){
set.add(nums);
}
//记录一个结果的最大长度值和序列的起始值
int maxLength = 0;
int start = 0;
for(int num : nums){
//如果当前值 - 1不包含在Set中,说明这是一个序列起点
if(!set.contains(num - 1)){
int currNum = num;
int currLength = 1;
//从当前值出发,如果set集合中还存在currNum + 1的值,说明是结果序列的值
while(set.contains(currNum + 1)){
currLength++;
currNums++;
}
//如果当前序列的长度大于最大长度,则更改最长长度和起始值
if(currLength > maxLength){
maxLength = currLength;
start = num;
}
}
}
int[] res = new int[maxLength];
//结果值为:start + i(第一个值就是1,第二个是start + 1, 第三个是start + 2、、、、、、)
for(int i = 0; i < maxLength; i++){
res[i] = start + i;
}
return res;
}
public static void main(String[] args){
int[] arr = {1,2,3,5,6,9};
int[] res = longestSub(arr);
for(int n : res){
System.out.pringln(n);
}
}
}