给定一个无序的整数类型数组,求最长的连续元素序列的长度

给定一个无序的整数类型数组,求最长的连续元素序列的长度。

例如:

给出的数组为[1000, 4, 2000, 1, 3, 2],

最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4

你需要给出时间复杂度在O(n)之内的算法

解析:

//用散列表,首先将数字都映射到散列表上,然后,对于每个数字,找到后就删除,然后向两边

//同时搜,只要搜到了就删除,最后求出长度。哈希表搜是O(1),因为每个数字只会添加一次,

//删除一次,所以复杂度是O(n)

class Solution {

扫描二维码关注公众号,回复: 14566582 查看本文章

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;

st.erase(v);

while(st.find(r+1)!=st.end()) st.erase(++r);

while(st.find(l-1)!=st.end()) st.erase(--l);

ans=max(r-l+1,ans);

}

return ans;

}

};

猜你喜欢

转载自blog.csdn.net/m0_62089210/article/details/128210493
今日推荐