leetcode HOT 100(128.连续最长序列)
这道题我们可以判断每个数current_num是否存在current_num-1,如果存在说明他不是开头数字,如果不存在说明他是开头数字,接下来再用while(current_num+1)遍历是否存在他后面的一个数字,如果存在,那么连续长度+1.
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> num_set = new HashSet<>();//将数组里面的数放入set集合这样就没有重复for (int num : nums) {num_set.add(num);}int longestStreak=0;//遍历set集合,判断当前数字是否有current_num-1for (Integer num : num_set) {if (!num_set.contains(num-1)){int current_num = num;int current_streak=1;while (num_set.contains(current_num+1)){current_num=current_num+1;current_streak++;}longestStreak = Math.max(longestStreak, current_streak);}}return longestStreak;}
}