int longestConsecutive(vector<int> &num) {
map<int, bool> map;
for (int i = 0; i < num.size(); i++)
{
map[num[i]] = true;
}
int maxLen = 0;
for (int i = 0; i < num.size(); i++)
{
if (map[num[i]] == true)
{
int len = 1;
int left = num[i] - 1;
while (map.count(left) && map[left] == true)
{
map[left] = false;
len++;
left--;
}
int right = num[i] + 1;
while (map.count(right) && map[right] == true)
{
map[right] = false;
len++;
right++;
}
maxLen = len > maxLen? len :maxLen;
}
}
return maxLen;
}
[LeetCode] Longest Consecutive Sequence
最新推荐文章于 2022-03-06 23:29:26 发布