问题描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
问题分析
假如不限制时间复杂度的话,实际上我们可以通过排序的形式求解此题。但关键是被套上了 O(n)的限制,问题的难点也在于此。我们可以有这样一种方法:遍历此数组,假设检索的当前元素为n,我们每次都检索 n-1 是否在此数组。这里存在的一个问题是,假如我们使用数组进行检索,那么算法的复杂度仍然为 O(n^2)。因此,我们使用unodered_set容器来存放元素(不适用set的原因是剔除其排序复杂度的影响)。假如 n-1 不在数组中,此时我们便开始检索 从n开始的连续元素数目。最终得到结果。需要解释的是,unordered_set的查找操作是可以在常数时间内完成的。
解决代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> sto(nums.begin(), nums.end());
int r = 0;
for (auto ele : nums) {
if (sto.find(ele-1) == sto.end()) {
int t = 0;
while (sto.find(ele++) != sto.end()) t++;
r = max(r, t);
}
}
return r;
}
};