## [LeetCode]Longest Consecutive Sequence

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(const vector<int> &nums) {
unordered_map<int, int> map;
int result = 0;
for (auto i: nums){
if (map.find(i) = map.end()){
int left = map.find(i - 1) != map.end() ? map[i - 1]: 0;
int right = map.find(i + 1) != map.end() ? map[i + 1]: 0;
int lenght = left + right + 1;
map[i] = length;
map[i - left] = length;
map[i + right] = length;
result = max(result, length);
}
}
return result;
}
};


class Solution {
public:
int longestConsecutive(const vector<int> &nums) {
unordered_map<int, bool> map;
for (auto i: nums) map[i] = false;
int result = 0;
for (auto i: nums){
if (map[i]) continue;
map[i] = true;
int length = 1;
for (int j = i + 1; map.find(j) != map.end(); j++){
map[j] = true;
length += 1;
}

for (int j = i - 1; map.find(j) != map.end(); j--){
map[j] = true;
length += 1;
}
result = max(result, length);
}
return result;
}
};


posted on 2017-10-16 10:35  月下之风  阅读(111)  评论(0编辑  收藏  举报