最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
解法1
先对数组进行排序,然后从小到大取最长的连续子串,有以下三种情况
- 前后两个元素相等,则跳过
- 前后两个元素不是相邻,重新计数
- 相邻,计数值+1
时间复杂度: nlogn
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size() == 0) return 0;
sort(nums.begin(), nums.end());
int t = 1;
int maxlen = 0;
for(int i = 0; i < nums.size() - 1; i++) {
if(nums[i+1] - nums[i] == 0) continue;
else if(nums[i+1] - nums[i] != 1) {
maxlen = max(maxlen, t);
t = 1;
}
else {
t++;
}
}
return maxlen>t? maxlen:t;
}
};
解法2
用哈希表和unorder_set实现
- 先用unorder_set去重
- 每一个连续的数都有前缀
- 若有前缀,则连续,继续判断有多少后缀,记录其长度
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> a;
for(auto num:nums ) {
a.insert(num);
}
int maxlen;
for(auto i: a) {
if(!a.count(i-1)) { //只有有前缀的才能继续判断,否则不连续
int t = 1;
int temp = i;
while(a.count(temp + 1)) {
temp++;
t++;
}
maxlen = max(maxlen, t);
}
}
return maxlen;
}
};