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:
/*algorithm: native way,
sort and counting
time O(nlgn) space O(1)
*/
int longestConsecutive(vector<int>& nums) {
int n = nums.size();
if(n < 2)return n;
int cnt = 1,maxCnt = 1;
sort(nums.begin(),nums.end());
for(int i = 1;i < n;i++){
if(nums[i-1]+1 ==nums[i])cnt++;
else if(nums[i-1] == nums[i])continue;
else cnt = 1;
maxCnt = max(cnt,maxCnt);
}
return maxCnt;
}
};
class Solution {
public:
/*algorithm:
scan and hash
time O(n) space O(n)
*/
int longestConsecutive(vector<int>& nums) {
unordered_set<int>tbl;
for(int i = 0;i < nums.size();i++){
tbl.insert(nums[i]);
}
int maxCnt = 0,cnt = 0;
for(auto it = tbl.begin(); it != tbl.end();it++){
int cur = *it;
int prev = cur-1,next=cur+1;
cnt = 1;
while(tbl.count(prev)){
tbl.erase(prev);
prev--;
cnt++;
}
while(tbl.count(next)){
tbl.erase(next);
next++;
cnt++;
}
maxCnt = max(maxCnt,cnt);
}
return maxCnt;
}
};