本题题目要求如下:
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.
本题虽然是hard,但是难度并不高,基本就是考hashmap的基本功。。只不过由于我理解题意错误,导致一直得到的是错误的结果基本算法就是把given array全存进hashset中。
然后对given array再一次遍历,如果找到比如元素array[i]我们就得不断寻找hashset中是否有array[i]+1和array[i]-1,如果有,继续找array[i]+2,array[i]-2,以此类推
便可得到O(N)的解,需要注意的一点是,没访问到一个hashset元素,就要从hashset中删除它,否则,时间复杂度就会变成O(N^2),当hashset被清空后,跳出。。
详细代码如下:
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> hash_set;
for (int i = 0; i < num.size(); ++i)
hash_set.insert(num[i]);
int max_size = 0;
int size;
for (int i = 0; i < num.size(); ++i) {
size = 1;
if (hash_set.size() == 0)
break;
int tmp = 1;
hash_set.erase(num[i]);
while (hash_set.find(num[i]+tmp) != hash_set.end()) {
++size;
hash_set.erase(num[i]+tmp);
++tmp;
}
tmp = 1;
while (hash_set.find(num[i]-tmp) != hash_set.end()) {
++size;
hash_set.erase(num[i]-tmp);
++tmp;
}
max_size = max(max_size, size);
}
return max_size;
}
};