128. Longest Consecutive Sequence
Hard
2363134FavoriteShare
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Accepted
244,769
Submissions
566,263
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int res=0;
unordered_set<int> st;//哈希表实现查找非常高效,因为unordered底层是哈希表实现
for(int i=0;i<nums.size();i++) st.insert(nums[i]);
for(int val:nums){//遍历vector
if(st.find(val)==st.end()) continue;
st.erase(val);
int pre=val-1,pos=val+1;
while(st.find(pre)!=st.end()) st.erase(pre--);
while(st.find(pos)!=st.end()) st.erase(pos++);
res=max(res,pos-pre-1);
}
return res;
}
};
本文深入探讨了如何在未排序整数数组中寻找最长连续元素序列的问题,提出了一个时间复杂度为O(n)的高效算法解决方案。通过使用哈希表进行高效查找,遍历数组并动态调整以找到最长连续序列,最终返回该序列的长度。
905

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



