Advertisement
exmkg

Untitled

Aug 23rd, 2024
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. class Solution {
  2.     public int longestConsecutive(int[] nums) {
  3.         // Add each number to a HashSet.
  4.         Set<Integer> set = new HashSet<>();
  5.         for (int n : nums) {
  6.             set.add(n);
  7.         }
  8.  
  9.         {99, 100, 4, 200, 1, 3, 2}
  10.  
  11.         [1, 2, 3, 4] [99, 100] [200]
  12.  
  13.         // T: O(n)
  14.         // S: O(n)
  15.    
  16.         int longest_streak = 0;
  17.         for (int n : set) {
  18.             // if (n is the beginning of a streak)
  19.             // Lookup works in O(1).
  20.             if (!set.contains(n - 1)) {
  21.                 int streak_start = n;
  22.                 int streak_end = n;
  23.  
  24.                 // Walk the streak to the last element.
  25.                 while (set.contains(streak_end + 1)) {
  26.                     streak_end++;
  27.                 }
  28.  
  29.                 // Update the value of the longest streak with the length of the current one.
  30.                 longest_streak = Math.max(longest_streak, streak_end - streak_start + 1);
  31.             }
  32.         }
  33.         return longest_streak;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement