给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.size() == 0)
return 0;
int res = 1;
map<int, int> m;
for (int i = 0; i < nums.size(); i++)
{
//遍历数组,如果map中不含此元素,将其放入到map中
if (m.find(nums[i]) == m.end())
{
m[nums[i]] = 1;
//如果map中存在比当前元素小1的元素,则跟上面一样获得连续子数组的第一个元素,进行更新。
if (m.find(nums[i] - 1) != m.end())
{
res = max(res, merge(m, nums[i] - 1, nums[i]));
}
if (m.find(nums[i] +1) != m.end())
{
res = max(res, merge(m, nums[i], nums[i] + 1));
}
}
}
return res;
}
int merge(map<int, int>& m, int less, int more)
{
//合并连续数组,并且更新数组的第一个元素和最后一个元素的value值为合并后的数组的长度。
int left = less - m[less] + 1;
int right = more + m[more] - 1;
int len = right - left + 1;
m[left] = len;
m[right] = len;
return len;
}
};