1public int longestConsecutive(int[] nums) {
2 if (nums.length == 0) return 0;
3
4 Set<Integer> numSet = new HashSet<>();
5 for (int num : nums) {
6 numSet.add(num);
7 }
8
9 int longestStreak = 0;
10
11 for (int num : numSet) {
12 // Check if num is the beginning of a sequence
13 if (!numSet.contains(num - 1)) {
14 int currentNum = num;
15 int currentStreak = 1;
16
17 // Increment currentNum to count the length of sequence
18 while (numSet.contains(currentNum + 1)) {
19 currentNum += 1;
20 currentStreak += 1;
21 }
22
23 longestStreak = Math.max(longestStreak, currentStreak);
24 }
25 }
26 return longestStreak;
27}