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.
Solution:
class Solution { public: set<int> dataset; int continousLength(int number) { int len = 0, l = number, r = number + 1; set<int>::iterator itr; while((itr = dataset.find(l)) != dataset.end()) { dataset.erase(itr); l--; len++; } while((itr = dataset.find(r)) != dataset.end()) { dataset.erase(itr); r++; len++; } return len; } int longestConsecutive(vector<int> &num) { int MaxLen = 0; dataset.clear(); for(int i = 0 ; i < num.size() ; i++) dataset.insert(num[i]); for(int i = 0;i < num.size();i++) MaxLen = max(continousLength(num[i]), MaxLen); return MaxLen; } };