練習使用unordered set
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 | class Solution { public: int longestConsecutive(vector<int>& Nums) { std::unordered_set<int> numSet; for (auto &num : Nums) numSet.insert(num); int ans = 0; for (auto &num : Nums) { int next = 1; while (numSet.count(num + next)) { numSet.erase(num + next); next++; } int prev = 1; while (numSet.count(num - prev)) { numSet.erase(num - prev); prev++; } ans = max(ans, next + prev - 1); } return ans; } }; |