forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamcho0608.java
More file actions
40 lines (35 loc) · 1.11 KB
/
samcho0608.java
File metadata and controls
40 lines (35 loc) · 1.11 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
40
import java.util.HashSet;
import java.util.Set;
// link: https://leetcode.com/problems/longest-consecutive-sequence/
// difficulty: Medium
class Solution {
// Problem:
// * nums is unsorted
// * return: length of longest consecutive elements sequence
// * req: O(N) time
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public int longestConsecutive(int[] nums) {
// Time Complexity: O(N)
// Space Complexity: O(N)
Set<Integer> uniq = new HashSet<>();
for(int num : nums) {
uniq.add(num);
}
// Time Complexity: O(N)
// * nested loop but is O(N) due to skipping non-root element
int maxLen = 0;
for(int num : uniq) {
// skip if num isn't the root(aka first number in the sequence)
if(uniq.contains(num - 1)) continue;
// count till end of consecutive sequence
int len = 1;
for(int i = 1; uniq.contains(num + i); i++) {
len++;
}
maxLen = Math.max(maxLen, len);
}
return maxLen;
}
}