1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <vector> #include <unordered_set> using std::unordered_set; using std::vector;
class Solution { public: int longestConsecutive(vector<int> &nums) { unordered_set<int> uset; for (int &num : nums) { uset.insert(num); } int longest = 0, curr = 0; for (auto &num : uset) { if (!uset.count(num - 1)) { curr = 1; while (uset.count(num + curr)) { curr++; } longest = std::max(curr, longest); } } return longest; } };
|