题目描述:
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.
Hide Tags Array
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.
Hide Tags Array
分析:要求一个数组中最长的连续子序列(公差为1)。对于未排序的数组,可以先排好序,然后对于长度大于2的数组,可以用双指针去遍历:若相邻两个元素值相差1,那么右指针继续右移,否则得到一个长度len,将其与全局的最大长度max比较,更新max。然后修改左指针,右指针右移一个位置,继续循环处理,直到右指针到数组最末端的下一个位置。
PS:如果本题为提及是否忽略重复元素,若要求去重后的递增连续序列最大长度,那么只需将数组排序后,去重,然后再按照本题的思路去求解即可以下是C++实现代码:
/**///16ms//*/
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size() < 2) //元素个数不足2个的,直接返回数组元素个数
return nums.size();
sort(nums.begin(),nums.end()); //将数组非递减排序
int i = 0, j = 1;
int max = 0,len = 0;
while(j != nums.size())
{
if(nums[j] - nums[j-1] == 1) //若相邻元素相差1,那么右指针右移一位
j++;
else //否则,求出当前的连续元素的长度,更新最大长度max
{
len = j - i;
i = j;
j++;
if(max < len)
max = len;
}
}
len = j - i; //此处处理最后一段连续递增序列
if(max < len)
max = len;
return max;
}
};