-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.java
More file actions
39 lines (30 loc) · 1.02 KB
/
LongestConsecutiveSequence.java
File metadata and controls
39 lines (30 loc) · 1.02 KB
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
// Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
// For example,
// Given [100, 4, 200, 1, 3, 2],
// The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
// Your algorithm should run in O(n) complexity.
class LongestConsecutiveSequence {
// added to twlvee"
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<Integer>();
for(int n: nums) {
set.add(n);
}
int maxLength = 0;
for(int n: set) {
if(!set.contains(n - 1)) {
int current = n;
int currentMax = 1;
while(set.contains(n + 1)) {
currentMax++;
n++;
}
maxLength = Math.max(maxLength, currentMax);
}
}
return maxLength;
}
}