题目
思路
1. 如果题目没有时间要求的话可以考虑直接排序然后统计的暴力解法
2. 题目要求时间复杂度为O(n),所以可以考虑使用一个哈希表used记录每个元素是否使用(被遍历过):
对于每一个元素首先判断其是否被遍历过,遍历过则pass,没遍历过才会有下面的故事:
1)先对该元素数轴上左边的数字(打印该元素)进行搜索,统计一下数目,并且遍历过的记录为true;
2)再先对该元素数轴上右边的数字(打印该元素)进行搜索,统计一下数目;
3)若记录的序列长度大于已记录的长度,则更新最长连续序列的长度。
eg: (摘自博客https://blog.youkuaiyun.com/sunnyyoona/article/details/18362525)
代码
class Solution {
public:
int longestConsecutive(vector<int> &nums) {
int ans = 0;
int len = nums.size();
// Map中的元素是自动按key升序排序
unordered_map<int,bool> used;
for(int i = 0; i < len; i++)
used[nums[i]] = false;
for(int i = 0; i < len; i++) {
if(used[nums[i]])
continue;
used[nums[i]] = true;
int temp = 1;
int j;
for(j = nums[i]+1; used.find(j) != used.end(); j++) {
used[j] = true;
temp++;
}
for(j = nums[i]-1; used.find(j) != used.end(); j--) {
used[j] = true;
temp++;
}
if(temp > ans)
ans = temp;
}
return ans;
}
};