
也可以使用排序,不过时间复杂度为O(nlogn).
int longestConsecutive(vector<int>& nums) {
set<int> st(nums.begin(), nums.end());
int longest = 0;
for(auto num:st){
if(!st.count(num-1)){
int length = 1;
int index = 1;
while(st.count(num+index)){
++length;
++index;
}
longest = max(longest,length);
}
}
return longest;
}
本文介绍了一种寻找数组中最长连续整数序列的算法。通过使用集合数据结构来提高查找效率,确保时间复杂度为O(n)。该算法首先将数组元素存入集合中,然后遍历集合并检查当前元素是否为连续序列的起始值,以此来确定最长连续序列的长度。
562

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



