Problem: 128. 最长连续序列
解析
哈希表
若使用双重循环来判断肯定没法达到O(n)的时间复杂度,可以考虑用哈希表来存储每个端点值对应连续区间的长度,关键是找到开始的端点值,只要找到开始的端点值,那么就可以往后遍历,直到找不到下一个端点值,这样就可以得到一个连续区间的长度,然后更新哈希表中的值,这样就可以在O(1)的时间复杂度内得到一个连续区间的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int longestConsecutive(vector<int>& nums) { int res = 0; unordered_set<int> hashSet; for (int i = 0; i < nums.size(); ++i) { hashSet.insert(nums[i]); }
for (auto e : hashSet) { int curNum = e; if (!hashSet.count(curNum - 1)) { int nowLongest = 1; while (hashSet.count(++curNum)) { ++nowLongest; } res = max(res, nowLongest); } } return res; } };
|