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.
使用一般的排序+查找算法,算法时间复杂度一定会超过o(n),故采用hash散列表可以有效解决该问题。下面为详细代码:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> hashTable;
unordered_set<int> visitTable;
for(int i=0;i<num.size();i++) hashTable.insert(num[i]);
int maxlen=INT_MIN;
int curlen;
for(int i=0;i<num.size();i++)
{
if(visitTable.find(num[i])!=visitTable.end()) continue;
curlen=1;
int left=num[i]-1;
while(hashTable.find(left)!=hashTable.end())
{
curlen++;
visitTable.insert(left);
left--;
}
int right=num[i]+1;
while(hashTable.find(right)!=hashTable.end())
{
curlen++;
visitTable.insert(right);
right++;
}
maxlen = maxlen>curlen?maxlen:curlen;
}
return maxlen;
}
};