-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestconsecutivesequence.cpp
More file actions
24 lines (19 loc) · 975 Bytes
/
longestconsecutivesequence.cpp
File metadata and controls
24 lines (19 loc) · 975 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> numSet(nums.begin(), nums.end()); // Create an unordered set to store all the numbers
int longestStreak = 0; // Initialize the longest streak to 0
for (int num : nums) {
if (numSet.find(num - 1) == numSet.end()) { // Check if the current number is the start of a sequence
int currentNum = num;
int currentStreak = 1; // Initialize the streak for the current sequence
while (numSet.find(currentNum + 1) != numSet.end()) { // Increment the current number until the sequence ends
currentNum++;
currentStreak++;
}
longestStreak = max(longestStreak, currentStreak); // Update the longest streak if necessary
}
}
return longestStreak;
}
};