Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
思路1: 排序聚合,然后遍历只需要和前一个元素比较,O(nlgn)+O(n)
思路2: 类似无向图连通性问题,对于每个未被mark的值,分别左右探测,累计长度,并mark经过的值。
int longestConsecutive(vector<int> &num) {
unordered_map<int,bool> used;
for(auto &e :num) used[e]=false;
int maxLen =1;
for(auto &e : used) {
if(e.second) continue;
int len=1;
for(int x = e.first-1;used.find(x)!=used.end();--x){
len++;
used[x]=true;
}
for(int x = e.first+1;used.find(x)!=used.end();++x){
len++;
used[x]=true;
}
maxLen = max(maxLen,len);
}
return maxLen;
}

本文介绍了一种高效算法,用于找出未排序整数数组中最长的连续元素序列,并提供了具体的实现代码。通过两种思路——排序聚合及类似无向图连通性的解决方法,实现了O(n log n)和O(n)的时间复杂度。
918

被折叠的 条评论
为什么被折叠?



