lc128

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> mp;
int mx = INT_MIN;
for (int i:nums) {
if (!mp[i]) {
mp[i] = mp[i+1] + mp[i-1] + 1;
mp[i+mp[i+1]] = mp[i];
mp[i-mp[i-1]] = mp[i];
if (mp[i] > mx) mx = mp[i];
}
}
return mx;
}
};