Skip to content

Commit f6aee9d

Browse files
committed
can be done by UF too
1 parent 98bc2aa commit f6aee9d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

UnionFind/longestConsecutive.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
/*
4+
finding the first element of the consecutive sequence and then finding the next ones.
5+
T.C- O(n)
6+
*/
7+
HashSet<Integer> hm = new HashSet<>();
8+
for (int i=0; i<nums.length; i++) {
9+
hm.add(nums[i]);
10+
}
11+
int longest = 0;
12+
13+
for (int num : hm) {
14+
int key = num;
15+
if(!hm.contains(key - 1)) {
16+
int count = 1;
17+
while(hm.contains(key + 1)) {
18+
count++;
19+
key++;
20+
}
21+
longest = Math.max(longest, count);
22+
}
23+
}
24+
return longest;
25+
}
26+
}
27+

0 commit comments

Comments
 (0)