tarmogoyf

O(n) in array

Dec 3rd, 2023
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.56 KB | Source Code | 0 0
  1. class Solution {
  2.     public int longestConsecutive(int[] nums) {
  3.         HashSet<Integer> set = new HashSet<>();
  4.         for(int i: nums) set.add(i);
  5.         int maxStreak = 0;
  6.  
  7.         for(int i: nums){
  8.             int  curStreak = 1;
  9.             if(!set.contains(i-1)) {
  10.                 int j = i+1;
  11.                 while(set.contains(j)) {
  12.                     curStreak ++;
  13.                     j ++;
  14.                 }
  15.                 maxStreak = Math.max(curStreak, maxStreak);              
  16.             }
  17.         }
  18.         return maxStreak;
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment