最长连续序列
题目:
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
解题思路:用HashSet将数组元素保存起来,再对每个元素判断集合中是否有他的下一个数即可
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet();
for(int num : nums) {
set.add(num);
}
int longest = 0;
for(int num : set) {
if(!set.contains(num - 1)) {
int curNum = num;
int curLong = 1;
while(set.contains(curNum + 1)) {
curNum++;
curLong++;
}
longest = Math.max(curLong, longest);
}
}
return longest;
}
}