题目128 最长连续序列
额外的收获:
写代码时尽量避免
for(int i = 0; i < nums.size(); ++i) { }
,在运行中会消耗大量的时间,应该使用for (auto num : nums)
这种形式的!
12.1 官方解析
下面的解法跟官方解析差不多!经过测试,无论自己写的解法还是官方解析,执行用时都是挺落后的,在所有 C++ 提交中击败了不到 20%的用户。
实在是惨不忍睹啊!
12.2 解法1
这个解法是LeetCode 101 中的解法,思路很清晰 。
把所有的数字放到一个哈希表中,然后不断地从哈希表中任取一值并删除它、在它之前、之后的所有连续数字,并更新目前最长连续序列长度!最终可以找到最长连续序列。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hash;
// 将所有元素存入哈希表中
for (const int num : nums) {
hash.insert(num);
}
// 最长连续序列长度
int result = 0;
// 直到哈希表为空,即所有的元素都已查找
while (!hash.empty()) {
int cur = *(hash.begin());
hash.erase(cur);
int next = cur + 1, prev = cur - 1;
while (hash.count(next)) {
hash.erase(next++);
}
while (hash.count(prev)) {
hash.erase(prev--);
}
result = max(result, next - prev - 1);
}
return result;
}
};
12.2 解法2
同样是使用哈希表来解决,不过这里是先找到数组中最小的元素,然后从一遍开始查找。
来看代码:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hash;
for (const int num : nums) {
hash.insert(num);
}
int result = 0;
for (const int value : hash) {
// 这样就找到了所有元素的最小值,从小到大开始遍历查找
if (!hash.count(value - 1)) {
int cur = value;
while (hash.count(++cur));
result = max(result, cur - value);
}
}
return result;
}
};