题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
题意:
输入没有排序的整型数组,目标是找到最长的连续元素个数,其中连续的定义为相邻元素之间只相差大小为1。希望可以使得算法在O(n)的时间复杂度运行。直观的思路是将源数组进行排序,有序的数组进行O(n)的遍历。那么要做到O(n)的排序,我还是直接使用了sort函数,参考前人的题解是使用set数据结构来实现排序。set内部是红黑树。当然思路都是希望将无序的数组转换为有序。
数组有序后,就可以更好的处理。只需O(n)遍历一遍即可找到最大的子区间,输出长度即可。测试用例有个坑,数组中会出现重复的元素,所以在判断元素的时候需要加上是否该元素出现过,若出现过则忽略不计。
代码:
int longestConsecutive(vector<int>& nums) {
if(nums.size() < 1)
return 0;
sort(nums.begin(), nums.end());
int maxLenth = 1, curLenth = 1;
for(int i = 0; i<nums.size(); i++)
{
if(i <nums.size()-1 && nums[i] == nums[i+1])
continue;
if(i < nums.size()-1 && nums[i] == nums[i+1]-1)
curLenth++;
else
{
if(curLenth > maxLenth)
maxLenth = curLenth;
curLenth = 1;
}
}
return maxLenth;
}
尽管我的解法严格意义上不算O(n),但是在最终的时间效率排名里,以上解法超过了98%的C++代码。// 有可能是我的网速比较快? // 还有一个可能是我调用的sort api,内部实现比较高效,所以整体影响不大。