Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
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.
T:
First store all numbers in a hashmap. Then traverse the array, for each number in the map, see if its previous numbers or next numbers also in the map.
A:
class Solution {
public:
int longestConsecutive(vector &num) {
unordered_map< int, bool > mark;
for(int i=0; i< num.size(); i++) {
mark[num[i]] = true;
}
int maxlen = 0;
for(int i=0; i< num.size(); i++) {
mark[num[i]] = false;
int mx = 1;
int v = num[i] + 1;
while(mark[v]) {
mark[v] = false;
mx++;
v++;
}
v = num[i] - 1;
while(mark[v]) {
mark[v] = false;
mx++;
v--;
}
if(mx > maxlen) {
maxlen = mx;
}
}
return maxlen;
}
};
No comments:
Post a Comment