From 1c69b0cfb3e9fd4f6f27677ab501a142b07c2b27 Mon Sep 17 00:00:00 2001 From: Stackingrule <38368554+Stackingrule@users.noreply.github.com> Date: Mon, 28 Dec 2020 16:01:49 +0800 Subject: [PATCH] feat:add Solution.cpp for 0128.Longest Consecutive Sequence --- .../Solution.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp diff --git a/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp new file mode 100644 index 0000000000000..8fd550c7e621c --- /dev/null +++ b/solution/0100-0199/0128.Longest Consecutive Sequence/Solution.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + int res = 0; + unordered_set set{nums.begin(), nums.end()}; + for (int num : nums) { + if (!set.count(num)) continue; + set.erase(num); + int pre = num - 1, next = num + 1; + while (set.count(pre)) set.erase(pre--); + while (set.count(next)) set.erase(next++); + res = max(res, next - pre - 1); + } + return res; + } +};