难度:困难
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
题目分析:
第一眼看到题目可能觉得会使用DP,因为是乱序的,所以用DP很难解。这里考虑使用set,将元素作为键存入set中,有两个作用:一个是去重;二个是方便查询。先将所有元素遍历一遍放入set中,在遍历,寻找每个序列的第一个元素,找到后在set中进行序列遍历并计数,找出最长序列。
参考代码:
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>
#include <assert.h>
#include <memory>
#include<queue>
#in