fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.HashSet;
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int longestConsecutive(int[] nums) {
  11. HashSet<Integer> set = new HashSet<>();
  12. for (int num : nums) set.add(num);
  13.  
  14. int maxLength = 0;
  15.  
  16. for (int num : set) {
  17. // Only start counting if it's the beginning of a sequence
  18. if (!set.contains(num - 1)) {
  19. int currentNum = num;
  20. int currentStreak = 1;
  21.  
  22. while (set.contains(currentNum + 1)) {
  23. currentNum++;
  24. currentStreak++;
  25. }
  26.  
  27. maxLength = Math.max(maxLength, currentStreak);
  28. }
  29. }
  30.  
  31. return maxLength;
  32. }
  33.  
  34. public static void main(String[] args) {
  35. int[] nums = {100, 4, 200, 1, 3, 2};
  36. System.out.println("Longest consecutive sequence length: " + longestConsecutive(nums)); // Output: 4
  37. }
  38. }
  39.  
  40.  
  41.  
  42.  
Success #stdin #stdout 0.15s 53576KB
stdin
Standard input is empty
stdout
Longest consecutive sequence length: 4