publicintlongestConsecutive(int[] nums){ int longestStreak = 0; //遍历 for (int num : nums) { int cur = num; int curStreak = 1; //计算num开头的连续序列长度 while (isContains(nums, cur + 1)) { cur++; curStreak++; } //更新最长长度 longestStreak = Math.max(longestStreak, curStreak); } return longestStreak; }
privatebooleanisContains(int[] nums, int num){ //遍历 for (int i : nums) { if (i == num) returntrue; } returnfalse; }
publicintlongestConsecutive(int[] nums){ //nums存入HashSet Set<Integer> set = new HashSet<>(); for (int num : nums) { set.add(num); } int longestStreak = 0; for (Integer num : set) { //num-1不存在的num作为序列的开头 if (!set.contains(num - 1)) { int cur = num; int curStreak = 1; //num+1是否存在 while (set.contains(cur + 1)) { cur++; curStreak++; } longestStreak = Math.max(longestStreak, curStreak); } } return longestStreak; }
时间复杂度:O(n) 虽然是 for 里嵌套了 while ,但是因为if (!set.contains(num - 1))(原因在优化时说过了),所以实际执行时间是O(n+n)。