solution
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> st;
for( auto n : nums ) { st.insert(n);}
int rst = 0;
for( int n : nums) {
int left = n - 1;
while( st.find(left) != st.end() ) {
st.erase(left);
left--;
}
int right = n + 1;
while(st.find(right) != st.end() ) {
st.erase(right);
right++;
}
rst = max(rst, right - left - 1);
}
return rst;
}
};想法很奇妙 , 但是我没想到union find 怎么解
本文介绍了一种求解最长连续序列的有效算法。通过使用哈希集合遍历整数数组,该算法能够在O(n)的时间复杂度内找到最长的连续元素序列。文章详细展示了算法的具体实现过程,包括如何通过左右扩展来确定连续序列的长度。
899

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



