class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int ans = 0;
unordered_map<int, pair<int, int> > M;
for(auto num : nums) {
if(M.find(num) != M.end()) continue;
int left = 0, right = 0;
if(M.find(num - 1) == M.end() && M.find(num + 1) == M.end()) M[num] = {num, num};
else if(M.find(num - 1) == M.end()) {
M[num] = {num, M[num + 1].second};
M[M[num + 1].second].first = num;
left = num;
right = M[num + 1].second;
}
else if(M.find(num + 1) == M.end()) {
M[num] = {M[num - 1].first, num};
M[M[num - 1].first].second = num;
left = M[num - 1].first;
right = num;
}
else {
M[num] = {M[num - 1].first, M[num + 1].second};
M[M[num - 1].first].second = M[num + 1].second;
M[M[num + 1].second].first = M[num - 1].first;
left = M[num - 1].first;
right = M[num + 1].second;
}
ans = max(ans, right - left + 1);
}
return ans;
}
};
leetcode 128. 最长连续序列
最新推荐文章于 2024-07-24 09:49:02 发布