Skip to content

Commit 7cb5fe6

Browse files
authored
Create Longest Consecutive Sequence Solution.java
1 parent 1397da6 commit 7cb5fe6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
Map<Integer, Integer> map = new HashMap<>();
4+
int maxLength = 0;
5+
for (int num : nums) {
6+
if (map.containsKey(num)) {
7+
continue;
8+
}
9+
int left = map.containsKey(num - 1) ? map.get(num - 1) : 0;
10+
int right = map.containsKey(num + 1) ? map.get(num + 1) : 0;
11+
int sum = left + right + 1;
12+
maxLength = Math.max(maxLength, sum);
13+
map.put(num, sum);
14+
map.put(num - left, sum);
15+
map.put(num + right, sum);
16+
}
17+
return maxLength;
18+
}
19+
}

0 commit comments

Comments
 (0)