Leetcode 128. 最长连续序列
题目
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
测试样例
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
题解
用一个哈希表记录出现的数字,然后遍历哈希表找到连续序列中的第一个数,然后增大长度,求解最长连续序列。详细过程见代码
代码
int longestConsecutive(vector<int>& nums) {
unordered_map<int,int> m;
for(auto& n:nums) m[n]=1;
int ans=0,x;
for(auto& n:m){
if(m.count(n.first-1) == 0){ //找到连续序列中的第一个数
x = n.first+1;
while(m.count(x) != 0){
m[n.first]++;
x++;
}
ans = max(ans,m[n.first]);
}
}
return ans;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。