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来记录,实际上也就是用map里的hash方法来解决这个问题。class Solution {
public:
int longestConsecutive(vector<int> &num) {
map<int, int> themap;
for(int ii = 0; ii < num.size(); ii ++) {
themap[num[ii]] = 1;
}
int max = 0;
for(int ii = 0; ii < num.size(); ii ++) {
int current = num[ii];
if(themap[current] == 0) continue;
themap[current] = 0;
int len = 1;
// Search to left.
int toleft = current - 1;
while(themap.find(toleft) != themap.end()) {
len ++;
themap[toleft] = 0;
toleft --;
}
// Search to right.
int toright = current + 1;
while(themap.find(toright) != themap.end()) {
len ++;
themap[toright] = 0;
toright ++;
}
if(len > max) {
max = len;
}
}
return max;
}
};