Leetcode 128 最长连续序列
有思路,大致思路(判断num-1是否在set里)是对的,但是num-1是否在set应该是外层判断条件,用来剪枝,跳过大部分情况,里面判断条件是num+1是否在set里。
思路总结:首先都存在Hashset中,访问一个数字,看是否是序列头(前面num-1是否存在在Hashset中),然后再通过num+1计算连续长度
//此代码为看它是否为结尾的元素
class Solution {
static public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
int maxlength = 0;
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
for (int num:set
) {
if(!set.contains(num+1)){
int currentnum = num;
int max = 1;
while(set.contains(currentnum-1)){
max++;
currentnum--;
}
if(max>maxlength) maxlength = max;
}
}
return maxlength;
}
}