Skip to content

Commit 8020e42

Browse files
authored
heozeop: longest consecutive sequence
1 parent 7fb858f commit 8020e42

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// time complexity: O(n)
2+
// spatail complexity: O(n)
3+
4+
class Solution {
5+
public:
6+
int longestConsecutive(vector<int>& nums) {
7+
unordered_set<int> exisingNum(nums.begin(), nums.end());
8+
9+
int maxLength = 0, length;
10+
for(int num : nums) {
11+
if(exisingNum.find(num - 1) != exisingNum.end()) {
12+
continue;
13+
}
14+
15+
length = 1;
16+
while(exisingNum.find(num + length) != exisingNum.end()) {
17+
++length;
18+
}
19+
20+
maxLength = max(maxLength, length);
21+
}
22+
23+
return maxLength;
24+
}
25+
};

0 commit comments

Comments
 (0)