`//用散列表,首先将数字都映射到散列表上,然后,对于每个数字,找到后就删除,然后向两边`
`//同时搜,只要搜到了就删除,最后求出长度。哈希表搜是O(1),因为每个数字只会添加一次,`
`//删除一次,所以复杂度是O(n)`
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int>st(num.begin(),num.end());
int ans=0;
for(auto v:num)
{
if(st.find(v)==st.end())continue;
int l=v,r=v;
while(st.find(r+1)!=st.end())st.erase(++r);
while(st.find(l-1)!=st.end())st.erase(--l);
ans=max(ans,r-l+1);
}
return ans;
}
};
longest-consecutive-sequence
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Description Given an unsorted array of integers, find the...
- 题目Given an unsorted array of integers, find the length of...
- Find Longest Continuous Increasing Subarray Algorithm Cre...
- Link to the problem Description Given an unsorted array o...
- Given an unsorted array of integers, find the length of t...