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
.
Your algorithm should run in O(n) complexity.
找最长连续子序列
这种题目,我一看到,就往dp想,但是,dp果断构造不出O(n)的动态转移方程。。。所以。。不会做。。。。。
用排序是n*log n的。。。不给力。。
看到“待字闺中”正好发布了一个这个题目的思路。。。。好吧。。。我还是太年轻了,还是已经忘记了。。。典型的并查集
用一个map来维护数字和其对应的index
一个father数组和一个count数组,用count更多的是为了平衡,防止union set退化
每次新来一个数x,判断是否已经在map中,如果在则跳过,如果不在,将其加入到并查集中,father是自己
然后union(x,x+1),接着union(x,x-1)
union的过程就是找到x和y分别各自的索引,然后找出该索引的father,然后更新father和count信息。
最后,遍历count数组,选出值最大的即可
class Solution {
public:
vector<int> father;
vector<int> count;
map<int,int> index;
int getIndex(int n){
map<int,int>::iterator it = index.find(n);
if(it==index.end())
return -1;
return it->second;
}
int getFather(int x){
if(x==father[x])
return x;
return getFather(father[x]);
}
void uni(int x,int y){
int xi = getIndex(x);
int yi = getIndex(y);
if(xi==-1 || yi==-1)
return;
int fx = getFather(xi);
int fy = getFather(yi);
if(count[fx]>count[fy]){
father[fy] = fx;
count[fx] = count[fx]+count[fy];
}else{
father[fx] = fy;
count[fy] +=count[fx];
}
}
int longestConsecutive(vector<int> &num) {
for(int i=0;i<num.size();i++){
if(getIndex(num[i])!=-1)
continue;
father.push_back(father.size());
count.push_back(1);
index.insert(pair<int,int>(num[i],father.size()-1));
uni(num[i],num[i]+1);
uni(num[i],num[i]-1);
}
int ma = 0;
for(int i=0;i<count.size();i++)
if(count[i]>ma)
ma=count[i];
return ma;
}
};