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

Longest Consecutive Sequence

2017-05-04 10:18 267 查看
Longest Consecutive Sequence

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.
解析:
若是连续的序列那么用该序列中任意一个数字都能找到该序列,那么遍历每个元素,找每个元素的序列,并把经过的元素都置为已访问,下次不再遍历这些元素。

代码:

class Solution {
public:
int longestConsecutive(vector<int>& nums) {

unordered_map<int,int>m;
for (int i=0; i<nums.size(); i++)
{
m[nums[i]]=1;
}
int ans=0;
int tempans=0;
for (int i=0; i<nums.size(); i++)
{
tempans=1;
if (m.count(nums[i])&&m[nums[i]])
{
m[nums[i]]=0;
int left=nums[i]-1;
while (m.count(left)&&m[left])
{
m[left--]=0;
tempans++;

}
int right=nums[i]+1;
while(m.count(right)&&m[right])
{
m[right++]=0;
tempans++;
}
}

if (ans<tempans)
{
ans=tempans;
}
}
return ans;

}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Longest Consecutive