leetcode consecutive sequence

mac2025-04-22  7

问题描述

给定一个无序的整数类型数组,求最长的连续元素序列的长度。 例如: 给出的数组为[100, 4, 200, 1, 3, 2], 最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4 你需要给出时间复杂度在O(n)之内的算法

解法

考虑使用hash表来存储。hash表没有重复元素。 stl中hash表是 unordered_set,他的查询和插入的时间复杂度都很低。 当寻找连续序列时,从一个数的左右两边寻找,寻找后将长度储存。 最关键的还是unordered_set的应用。

class Solution { public: int longestConsecutive(vector<int> &num) { unordered_set<int>s(num.begin(),num.end()); int m=0; for(int i=0;i<num.size();i++){ int n = num[i]; int pre = n-1,next = n+1; if(s.erase(n)==1){ while(s.erase(pre)==1){ pre--; } while(s.erase(next)==1){ next++; } } m = max(m,next-pre-1); } return m; } };
最新回复(0)