Leetcode 128 Solution

This article provides solution to leetcode question 128 (longest-consecutive-sequence)

https://leetcode.com/problems/longest-consecutive-sequence

Solution

class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<int> s;
for (auto num : nums) s.insert(num);
int max_count = 0; for (auto num : nums) { if (s.find(num) == s.end()) continue;
s.erase(num); int count = 1;
int lnum = num - 1; while (s.find(lnum) != s.end()) { s.erase(lnum--); count++; }
int rnum = num + 1; while (s.find(rnum) != s.end()) { s.erase(rnum++); count++; }
max_count = max(max_count, count); }
return max_count; } };