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

Longest Consecutive Sequence

2016-08-31 15:19 190 查看
一、问题描述

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.
二、思路

本题题意是求出最大的连续序列的长度。我们先对数组排序,然后遍历整个数组,遇到相同元素,跳过,遇到满足连续特性的数组,我们将临时变量加一,遇到不满足条件的元素,我们首先判断当前临时变量是否大于等于最大长度,如果满足,则更新max_len,同时不管是否满足条件都将临时变量置一,意味着重新开始。最后挑出循环后继续判断临时变量是否大于最大长度,如果大于,则需要更新最大长度。

三、代码

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
sort(nums.begin(), nums.end());
int temp = 1, max_len = 1;
for(int i = 1; i < nums.size(); ++i){
if(nums[i] == nums[i - 1])
continue;
else if(nums[i - 1] + 1 == nums[i]){
temp++;
}else{
if(temp >= max_len){
max_len = temp;
}
temp = 1;
}
}
if(temp > max_len){
max_len = temp;
}
return max_len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode