题目:
用哈希表,虽然是 for 循环里面一个 while,但是整体来看每个元素只访问了一次。核心思想是每次找到连续序列的最小值,然后依次找这个连续序列后面的连续元素。注意遍历时要按 uset 遍历,避免遍历 nums 时重复元素太多。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <vector> #include <unordered_set>
using std::unordered_set; using std::vector;
class Solution { public: int longestConsecutive(vector<int> &nums) { int curr, longest = 0; unordered_set<int> uset(nums.begin(), nums.end()); for (auto &num : uset) { if (!uset.count(num - 1)) { curr = 1; while (uset.count(num + curr)) { curr++; } longest = std::max(longest, curr); } } return longest; } };
|
也可以找一个序列中最大的那个:
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 27 28 29
| #include <vector> #include <unordered_set> #include <algorithm> using std::vector; using std::unordered_set;
class Solution { public: int longestConsecutive(vector<int> &nums) { unordered_set<int> uset(nums.begin(), nums.end());
int n = nums.size(); int cnt, max_val = 0;
for (int curr : uset) { if (uset.count(curr + 1) != 0) continue; cnt = 1; while (uset.count(curr - cnt) != 0) cnt++; max_val = std::max(max_val, cnt); } return max_val; } };
|