add: 220705

This commit is contained in:
Eat-Swap 2022-07-06 00:09:46 +08:00
parent 0bd6894a70
commit 0ecc6afcec
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
1 changed files with 25 additions and 0 deletions

25
cpp/2207/220705.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <unordered_set>
#include <vector>
/**
* 128. Longest Consecutive Sequence
* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
* You must write an algorithm that runs in O(n) time.
*/
class Solution {
public:
int longestConsecutive(const std::vector<int>& nums) {
std::unordered_set<int> s(nums.begin(), nums.end());
int ans = 0;
for (int i : s) {
if (s.count(i - 1))
continue;
int cur = i, ca = 1;
for (; s.count(1 + cur); ++cur)
++ca;
ans = std::max(ans, ca);
}
return ans;
}
};