Untitled
class Solution { public: int longestConsecutive(vector<int>& nums) { int ans = 0; unordered_set<int> S; for (int n : nums) S.emplace(n); int cnt = 2; while (S.size() > 0) { int tmp = 1; int n = *S.begin(); S.erase(n); int i = n; while (S.find(i+1)!=S.end()) { tmp++; S.erase(i+1); ++i; } i = n; while (S.find(i-1)!=S.end()) { tmp++; S.erase(i-1); --i; } ans = max(ans, tmp); } return ans; } // 9, 1, 4, 7, 3, -1, 0, 5, 8, 6 // 9 - 8 // 1 - 0 // 4 - 3 // 7 - 6 // 0 - -1 // 5 - 4 // 8 - 7 // 6 - 5 };
Leave a Comment