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> &num) {
if(num.size()<=0)
return 0;
else if(num.size()==1)
return 1;
sort(num.begin(),num.end());
int temp=1;
int max=1;
for(int i=1;i<num.size();i++)
{
if(num[i]-num[i-1]==1)
{
temp++;
}
else if(num[i]-num[i-1]==0)
continue;
else
{
if(temp>max)
max=temp;
temp=1;
}
}
if(temp>max)
max=temp;
return max;
}
};