class Solution {
public:
int longestConsecutive(vector<int>& nums) {
map<int,int> tmp;
int max = 0;
for (int i = 0; i < nums.size(); i++)
{
if (tmp.find(nums[i]) == tmp.end())
{
int l = tmp.find(nums[i]-1) != tmp.end()?tmp[nums[i]-1]:0;
int r = tmp.find(nums[i]+1) != tmp.end()?tmp[nums[i]+1]:0;
int n = l+r+1;
if (n>max)
{
max = n;
}
tmp[nums[i]] = n;
tmp[nums[i] - l] = n;
tmp[nums[i] + r] = n;
}
}
return max;
}
};
public:
int longestConsecutive(vector<int>& nums) {
map<int,int> tmp;
int max = 0;
for (int i = 0; i < nums.size(); i++)
{
if (tmp.find(nums[i]) == tmp.end())
{
int l = tmp.find(nums[i]-1) != tmp.end()?tmp[nums[i]-1]:0;
int r = tmp.find(nums[i]+1) != tmp.end()?tmp[nums[i]+1]:0;
int n = l+r+1;
if (n>max)
{
max = n;
}
tmp[nums[i]] = n;
tmp[nums[i] - l] = n;
tmp[nums[i] + r] = n;
}
}
return max;
}
};
评论
发表评论