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

Leetcode--Longest Consecutive Sequence

2014-10-10 20:17 330 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: