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.
这种思想主要是运用了Map的自动排序的特性
class Solution {
public:
int longestConsecutive(vector<int> &num) {
std::map<int, int> countMap;
int len = num.size();
for (int i=0; i<len; i++)
{
if (countMap[num[i]] == 0)
{
countMap[num[i]] = 1;
}
}
int curVal = 0;
int maxVal = 0;
std::map<int, int>::iterator itr = countMap.begin();
int pre = itr->first;
curVal++;
maxVal++;
++itr;
while (itr != countMap.end())
{
if (itr->first == pre+1)
{
curVal++;
if (curVal > maxVal)
{
maxVal = curVal;
}
}
else
{
curVal = 1;
}
pre = itr->first;
++itr;
}
return maxVal;
}
};
还有一种思想 参考:http://blog.youkuaiyun.com/aivin24/article/details/23873943
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int,int> f;
int max_v(1);
for(auto val: num)
f[val] = 1;
for(auto val: num){
int left = val - 1, right = val + 1;
while (f[left]){
f[left] = 0;
left--;
}
while(f[right]){
f[right] = 0;
right++;
}
max_v = max(max_v,right-left-1);
}
return max_v;
}
};