class Solution {
public:
int longestConsecutive(vector<int> &num) {
int n = num.size();
if(n <= 0) return 0;
if(n == 1) return 1;
sort(num.begin(), num.end());
int maxAll = 1;
int maxLast = 1;
vector<int>::iterator cit = num.begin();
vector<int>::iterator lit = cit;
cit++;
while(cit!=num.end()) {
int del = *cit - *lit;
if(del == 0) {
cit ++;
lit ++;
continue;
}
if(del == 1) maxLast ++;
else maxLast = 1;
maxAll = max(maxAll, maxLast);
cit ++;
lit ++;
}
return maxAll;
}
};
欢迎关注微信公众号——计算机视觉:

本文介绍了一种寻找整数数组中最长连续元素序列的算法。通过先排序再遍历的方法,实现了对输入数组的有效处理,并返回了最长连续序列的长度。此算法适用于需要找出连续整数序列的应用场景。
647

被折叠的 条评论
为什么被折叠?



