128. 最长连续序列
2 min
题目
思路
使用哈希集合去重并快速查找,从每个连续序列的起点开始扩展
复杂度
- 时间复杂度:
- 空间复杂度:
代码
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int>st;
for(int i = 0 ;i < nums.size();i++){
st.insert(nums[i]);
}
int ans = 0;
int nowlen = 1;
for(auto i:st){
if(!st.count(i-1))
{
while(st.count(i+nowlen)){
nowlen++;
}
ans = max(ans,nowlen);
nowlen = 1;
}
}
return ans;
}
};