-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path128.cpp
More file actions
23 lines (20 loc) · 705 Bytes
/
128.cpp
File metadata and controls
23 lines (20 loc) · 705 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> us(nums.begin(), nums.end());
int ans = 0;
for (int num : us) {
// if num-1 is in the set, it means that num is part of some consecutive sequence. We don't need to calculate the sub-sequence!!
if (us.find(num-1) == us.end()) {
int startTarget = num;
int currentLen = 1;
while (us.find(startTarget+1) != us.end()) {
startTarget += 1;
currentLen += 1;
}
ans = max(ans, currentLen);
}
}
return ans;
}
};