题目:最长连续序列:
题目描述:
网址:https://leetcode-cn.com/problems/longest-consecutive-sequence/
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
解题思路:
c++ 中 map可以自动从小到大对 key 排序;所以首先将所有的数据放入map;
然后从第一个map数据开始遍历;如果 当前map.key == 上一个map.key + 1 ;将 当前记录连续序列的长度tmp +1,反之 比较tmp 和 ListLen(最长连续序列的长度), tmp = 1 ,从新计数 ;
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size() == 0)
return 0 ;
int c_i = 0 ;
map<int , int> data ;
int ListLen = 0 ;
while (c_i < nums.size())
{
data[nums[c_i]] ++ ;
c_i ++ ;
}
int tmp = 1 ;
int precurrent = data.begin()->first ;
for(auto tdata : data)
{
if (precurrent == tdata.first - 1)
tmp ++ ;
else
{
ListLen = ListLen < tmp ? tmp : ListLen ;
tmp = 1 ;
}
precurrent = tdata.first ;
}
//保证每一个tmp都与ListLen做过比较;
ListLen = ListLen < tmp ? tmp : ListLen ;
return ListLen ;
}
};