Skip to content

Commit 3d8228e

Browse files
authored
Merge pull request neetcode-gh#70 from Pegasus02K/patch-5
Create 128-Longest-Consecutive-Sequence.cpp
2 parents a7da506 + 7cc1ae6 commit 3d8228e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
int longestConsecutive(vector<int>& nums) {
4+
unordered_set<int> hs;
5+
for (int n : nums) {
6+
hs.insert(n);
7+
}
8+
9+
int longest = 0;
10+
for (int n : nums) {
11+
// if n-1 is not in the set, the element can be the start of a sequence
12+
if (hs.find(n - 1) == hs.end()) {
13+
int length = 1;
14+
while (hs.find(n + length) != hs.end())
15+
++length;
16+
longest = max(longest, length);
17+
}
18+
}
19+
return longest;
20+
}
21+
};

0 commit comments

Comments
 (0)