题意是求数组中的数,最长连续能是多少,例如有1,2,3,4,5这些数在数组中不要求连续,只需要存在即可。题目要求用o(n)的复杂度解决。本质就是查找x以及x+1这样下去的数是否存在于nums中,将查找做到o(1)即可。所以将nums中所有的数都先存入哈希集合中。遍历哈希集合即可
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int ans=0;
unordered_set<int>st(nums.begin(),nums.end());//要on所以想到集合
for(int x:st)
{
if(st.count(x-1)>0)continue;//如果x-1存在的话就不用x当作起点了
int y=x+1;
while(st.count(y)>0)y++;
ans=max(ans,y-x);
}
return ans;
}
};
别忘记在循环中不断更新最大值。