问题的思路为:将数组保存在hashset中,从某一数开始,分别向前递减向后递增遍历,若遍历的数在set中,则删除且count++,最后找到最大的count数即可。
代码
class Solution
{
public:
int longestConsecutive(vector<int> &num)
{
count = 1;
maxCount = 1;
set<int> tempSet;
for(int i = 0; i < num.size(); ++i)
{
tempSet.insert(num[i]);
}
while(!tempSet.empty())
{
getCount(tempSet, *tempSet.begin());
}
return maxCount;
}
void getCount(set<int> &tempSet, int val)
{
int bigger = val + 1;
int smaller = val - 1;
tempSet.erase(val); //此处注意要记得删除当前值val
while(tempSet.find(bigger)!=tempSet.end())
{
tempSet.erase(bigger);
count++;
bigger++;
}
while(tempSet.find(smaller)!=tempSet.end())
{
tempSet.erase(smaller);
count++;
smaller--;
}
if(count>maxCount)
maxCount = count;
count = 1;
}
private:
int count;
int maxCount;
};