- 最长连续序列
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
思考:
复杂度为N则应该一遍遍历就能够得到答案。复杂度为n则最先想到时空置换。最常见的就是设定一个很长的数组但是这个题目没有数字大小的上限所以也不行。今天是第一天回归leedcode之前的解题能力已经丢了一大半了(虽然本来也没多少)。想了会感觉毫无思路,看到tag里面的并查集,想了想发现已经忘记了。。只能看看大神们的答案了。
官方的解答一是使用了哈希表的特性制作了一个特殊了复杂度为N的双重循环。外循环的时候我们要做的是找到一个x数它不存在x-1的前驱数。找到之后进入内循环,利用哈希表查找O(1)的特性寻找longestStreak。内循环中每个数字仅会出现一次,因此复杂度为外循环+内循环=O(n)+O(n)=O(n)
官方解答:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set;
//FORREACH循环将数值插入哈希表
for (const int& num : nums) {
num_set.insert(num);
}
//最长连续序列
int longestStreak = 0;
for (const int& num : num_set) {
if (!num_set.count(num - 1)) {//如果不存在当前数字-1的数
int currentNum = num;
int currentStreak = 1;//当前序列长度加1
while (num_set.count(currentNum + 1)) {//while内层循环计算序列长度
currentNum += 1;
currentStreak += 1;
}
longestStreak = max(longestStreak, currentStreak);//序列长度比较找出最长
}
}
return longestStreak;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/zui-chang-lian-xu-xu-lie-by-leetcode-solution/
来源:力扣(LeetCode)
另一个大佬的版本非常精简的使用了并查集的思想。解题思路都是用了哈希表。实现方法有所区别
作者:leck
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/cbing-cha-ji-xie-fa-dai-ma-ji-duan-by-leck/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
unordered_map<int,int> a,b;
int find(int x){
return a.count(x)?a[x]=find(a[x]):x;//unordered_map.count 返回匹配给定主键的元素的个数
}
int longestConsecutive(vector<int>& nums) {
//下述代码等同于for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
for(auto i:nums)//将nums的数赋值到a数组
a[i]=i+1;
int ans=0;
for(auto i:nums){
int y=find(i+1);//查找当前个数值+1的数,如果有则继续如果没有则返回当前数值
ans=max(ans,y-i);//y-i就是序列长度
}
return ans;
}
};
两个版本第一个查找返回的是序列长度。第二个是序列的最后一个数,用差值来得出序列长度。