題目:128. 最長連續序列
給定一個未排序的整數數組,找出最長連續序列的長度。
要求算法的時間複雜度爲 O(n)。
示例:
輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度爲 4。
時間複雜度爲O(n),排序算法排除,第一時間想到的就是HashMap,c++裏邊的map就是有序表,把所有元素都插進去之後自然是有序的,然後在再遍歷有序表看最長連續是多少就比較簡單了,時間上需要遍歷一次數組和Map,複雜度爲O(n),空間複雜度易得爲O(n)。
代碼如下:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.empty())
return 0;
map<int,int> order;
map<int, int>::iterator iter;
int last=nums[0],ans=0,cnt=0;
//插入元素,有序表默認從小到大
for(int i=0;i<nums.size();i++){
order[nums[i]]=1;
}
//遍歷有序表
for(iter=order.begin();iter!=order.end();iter++){
int num= iter->first;
//前面有連續序列
if(num==last+1){
cnt++;
last++;
}
//無連續序列
else {
last=num;
cnt=1;
}
ans=max(cnt,ans);
}
return ans;
}
};
運行結果:
官方的題解我也想到過,但是沒有仔細推算過時間複雜度,本質上是用map的快速查詢,實現感覺也不是很出彩,倒是在別的題解看到一個賊簡潔的的,也是並查集:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/cbing-cha-ji-xie-fa-dai-ma-ji-duan-by-leck/
思路是:
- 初始化的時候先把數組裏每個元素初始化爲他的下一個數;
- 並的時候找他能到達的最遠的數字就可以了。
代碼:
class Solution {
public:
unordered_map<int,int> a,b;
int find(int x){
return a.count(x)?a[x]=find(a[x]):x;
}
int longestConsecutive(vector<int>& nums) {
for(auto i:nums)
a[i]=i+1;
int ans=0;
for(auto i:nums){
int y=find(i+1);
ans=max(ans,y-i);
}
return ans;
}
};
運行結果: