class Solution {//用set判断一个元素是否存在于集合中O(logn)。用到的一个优化是连续的x个数对应的序列长度都是一样的,可以通过判断元素是否遍历过来避免查找。没有这一步会超时。有的也用<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px; background-color: rgb(245, 250, 226);">unordered_set代替set,据说这是hash表,O(1),更快。</span>
public:
int longestConsecutive(vector<int> &v) {
if(v.size()==0)return 0;
set<int>st,st2;
set<int>::iterator bg,ed;
int i=0,tmp1,tmp2,ans=0;
for(i=0;i<v.size();++i)
st.insert(v[i]);
for(bg=st.begin(),ed=st.end();bg!=ed;bg++){
if(st2.find(*bg)!=st2.end())continue;
tmp1=*bg-1;
while(st.find(tmp1)!=ed)st2.insert(tmp1--);
tmp2=*bg+1;
while(st.find(tmp2)!=ed)st2.insert(tmp2++);
tmp1=tmp2-tmp1-1;
if(tmp1>ans)
ans=tmp1;
}
return ans;
}
};
http://oj.leetcode.com/problems/longest-consecutive-sequence/[LeetCode]longest consecutive sequence
最新推荐文章于 2025-03-19 23:17:40 发布