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.
代码如下:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
map<int,int> hashMap;
int result = 0;
for(int i=0;i<num.size();i++)
{
if(hashMap.find(num[i]) == hashMap.end())
{
int left=0,right = 0;
if(hashMap.find(num[i]-1) == hashMap.end())
left = 0;
else
left = hashMap[num[i]-1];
if(hashMap.find(num[i]+1) == hashMap.end())
right = 0;
else
right = hashMap[num[i]+1];
hashMap[num[i]] = right+left+1;
result = max(result,right+left+1);
hashMap[num[i]-left] = right+left+1;
hashMap[num[i]+right] = left+right+1;
}
else
continue;
}
return result;
}
};
对数据结构进行修改,代码如下:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int,int> hashMap;
int result = 0;
for(int i=0;i<num.size();i++)
{
if(hashMap.find(num[i]) == hashMap.end())
{
int left=0,right = 0;
if(hashMap.find(num[i]-1) == hashMap.end())
left = 0;
else
left = hashMap[num[i]-1];
if(hashMap.find(num[i]+1) == hashMap.end())
right = 0;
else
right = hashMap[num[i]+1];
hashMap[num[i]] = right+left+1;
result = max(result,right+left+1);
hashMap[num[i]-left] = right+left+1;
hashMap[num[i]+right] = left+right+1;
}
else
continue;
}
return result;
}
};
另一种方法,就是先排序然后求连续子序列即可,代码如下:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.size() == 0) {
return 0;
}
sort(nums.begin(), nums.end());
int len = 0;
int temp = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i - 1]) continue;
if (nums[i] == nums[i - 1] + 1) {
temp++;
} else {
len = max(len, temp);
temp = 1;
}
}
len = max(len, temp);
return len;
}
};