[编程题] lc:128. 最长连续序列
题目描述
输入输出
见上
思路
逐个的拿出数组中的元素,把它假想为是最小的数。然后累加1且去哈希表中找是否有,如果有count就加1、然后知道set中没有的时候得出本次count的值。又一次拿出数组中的第2个元素执行如上操作。最终返回一个最长的count值。
Java代码
import java.util.*;
class Solution {
public static int longestConsecutive(int[] nums) {
//极限值
if(nums==null || nums.length==0){return 0;}
int max = 1;
int count = 1;
//哈希表
HashSet<Integer> set = new HashSet<Integer>();
for(int num : nums){
set.add(num);
}
//遍历数组,拿出1个元素执行1轮操作,得出一个count值
for(int i = 0;i<nums.length;i++){
//默认拿出这次认为是最小的值
int min = nums[i];
//逐渐递增得出连续递增序列
while(true){
int cur = min+1;
if(set.contains(cur)){
count++;
min = cur;
}else{
max = count>max?count:max;
count=1; //count回归1计数
break;
}
}
}
return max;
}
}