From 0ecc6afcec1ece934f0016ac76d635475793b852 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Wed, 6 Jul 2022 00:09:46 +0800 Subject: [PATCH] add: 220705 --- cpp/2207/220705.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 cpp/2207/220705.cpp diff --git a/cpp/2207/220705.cpp b/cpp/2207/220705.cpp new file mode 100644 index 0000000..32650e3 --- /dev/null +++ b/cpp/2207/220705.cpp @@ -0,0 +1,25 @@ +#include +#include + +/** + * 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& nums) { + std::unordered_set 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; + } +};