您的位置:首页 > 产品设计 > UI/UE

[leetcode] 【数组】128. Longest Consecutive Sequence

2016-05-22 02:03 711 查看
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,

Given [100, 4, 200, 1, 3, 2],

The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

题解

题意是要找到最多的 连续数字的个数,首先想到的是排序,但是排序的话时间复杂度不满足O(n)的要求。

满足O(n)要求的话,可以想到借助哈希表来标注,这样遍历每个数时分别往前、往后找就可以找到连续的数字。

//cpp
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
map<int,bool> isused;
for(auto i :nums) isused[i]=false;
int longest=0;
for(auto i:nums)
{
if(isused[i]) continue;
int len=1;
isused[i]=true;
for(int j=i+1;isused.find(j)!=isused.end();j++)
{
len++;
isused[j]=true;
}
for(int j=i-1;isused.find(j)!=isused.end();j--)
{
len++;
isused[j]=true;
}
longest=max(longest,len);
}
return longest;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: