Skip to content

Commit d27b620

Browse files
authored
Update Longest Consecutive Sequence.java
1 parent 7412f6f commit d27b620

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed
Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
class Solution {
22
public int longestConsecutive(int[] nums) {
3-
Map<Integer, Integer> map = new HashMap<>();
4-
int maxLength = 0;
3+
Set<Integer> set = new HashSet<>();
54
for (int num : nums) {
6-
if (map.containsKey(num)) {
7-
continue;
5+
set.add(num);
6+
}
7+
int maxLength = 0;
8+
for (int num : set) {
9+
if (!set.contains(num - 1)) {
10+
int currNum = num;
11+
int currentLength = 1;
12+
while (set.contains(currNum + 1)) {
13+
currNum++;
14+
currentLength++;
15+
}
16+
maxLength = Math.max(currentLength, maxLength);
817
}
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);
1618
}
1719
return maxLength;
18-
}
20+
}
1921
}

0 commit comments

Comments
 (0)