128. Longest Consecutive Sequence
problem description
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.algorithm thought
code
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(),nums.end());
int best=0;
for(int val:nums)
{
if(s.count(val-1)) continue;
int y=val+1;
while(s.count(y))
{
y++;
}
best=max(best,y-val);
}
return best;
}
};algorithm analysis
Last updated