1.问题描述
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.
2.问题分析
题目是让我们求一个整数数组中,存在最长连续整数序列的长度。同时要是O(n)解法。考虑到这个数组是无序的,可以考虑用unordered_map<int, bool>
来作数据结构表示该整数数组中数的遍历状态。true为访问过,false为初始态未访问的。接下来我们只要遍历这个无序map,对于每一个原数组中出现的数i,判断i++/i- -是否也存在,若存在则给最长长度加1即可,同时状态要从false修改为访问过的true。因此,只需要O(n)即可求解。
3.源代码
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
class MySolution
{
public:
int the_longest_consecutive(const vector<int> &num)
{
int longest_length = 0;
unordered_map<int, bool> used;
for (auto i : num)
used[i] = false;
for (auto i : num)
{
if (used[i])
continue;
int cur_length = 1;
used[i] = true;
for (int j = i + 1; used.find(j) != used.end(); j++)
{
cur_length++;
used[j] = true;
}
for (int j = i - 1; used.find(j) != used.end(); j--)
{
cur_length++;
used[j] = true;
}
longest_length = max(longest_length, cur_length);
}
return longest_length;
}
};
int main()
{
vector<int> num = {100, 4, 200, 1, 3, 2};
MySolution test;
cout << test.the_longest_consecutive(num) << endl;
return 0;
}
4.reference
[1]Creative Commons: http://creativecommons.org/licenses/by-nc-sa/3.0/
[2]https://github.com/soulmachine/leetcode