1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | package com.demo.s128;
  import java.util.HashSet; import java.util.Set;
 
 
 
 
 
 
 
 
 
 
  public class Solution {     public int longestConsecutive(int[] nums) {                  Set<Integer> num_set = new HashSet<Integer>();         for (int num : nums) {             num_set.add(num);         }                  int longestStreak = 0;                  for (int num : num_set) {                          if (!num_set.contains(num - 1)) {                 int currentNum = num;                 int currentStreak = 1;                                  while (num_set.contains(currentNum + 1)) {                     currentNum += 1;                     currentStreak += 1;                 }                                  longestStreak = Math.max(longestStreak, currentStreak);             }         }
          return longestStreak;     } }
   |