-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSeq.java
More file actions
39 lines (32 loc) · 1003 Bytes
/
Copy pathLongestConsecutiveSeq.java
File metadata and controls
39 lines (32 loc) · 1003 Bytes
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
import java.util.HashSet;
/**
* Leetcode problem #128, Longest Consecutive Sequence
* https://leetcode.com/problems/longest-consecutive-sequence/
*/
public class LongestConsecutiveSeq {
public static void main(String[] args) {
int[] nums = new int[] { 0, 3, 7, 2, 5, 8, 4, 6, 0, 1 };
System.out.println(longestConsecutive(nums));
}
public static int longestConsecutive(int[] nums) {
if (nums.length == 0)
return 0;
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int maxLength = 0;
for (int num : set) {
if (!set.contains(num - 1)) {
int curr = num;
int currLength = 1;
while (set.contains(curr + 1)) {
curr++;
currLength++;
}
maxLength = Math.max(maxLength, currLength);
}
}
return maxLength;
}
}