unordered_map 也算O(1), ^ _ ^!
不能用mp值定义为坐标,因为会有0值的存在
WA代码
/*
* @lc app=leetcode id=128 lang=cpp
*
* [128] Longest Consecutive Sequence
*/
// @lc code=start
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int,int> mpL,mpR;
int N = nums.size();
int ans = 0;
int L,R;
for(int i=0;i<N;i++){
L = mpL[nums[i]-1];
R = mpR[nums[i]+1];
if(L!=0 && R!=0){
mpL[R] = L;
mpR[L] = R;
ans = max(ans,R-L+1);
}else if(L!=0){
mpL[nums[i]] = L;
mpR[nums[i]] = nums[i];
ans = max(ans,nums[i]-L+1);
}else if(R!=0){
mpR[nums[i]] = R;
mpL[nums[i]] = nums[i];
ans = max(ans,R-nums[i]+1);
}else{
mpL[nums[i]] = mpR[nums[i]] = nums[i];
ans = max(ans,1);
}
}
return ans;
}
};
// @lc code=end
AC代码:
/*
* @lc app=leetcode id=128 lang=cpp
*
* [128] Longest Consecutive Sequence
*/
// @lc code=start
class Solution {
public:
// 因为存在0值
// 所以map中值不能定义为坐标
// 定义为长度比较合理
int longestConsecutive(vector<int>& nums) {
unordered_map<int,int> mpL,mpR;
int N = nums.size();
int ans = 0;
int L,R;
for(int i=0;i<N;i++){
// 已经处理过的值不再处理,因为不能保证边界中间节点值是合法的。
if(mpL[nums[i]] != 0 || mpR[nums[i]] != 0) continue;
L = mpL[nums[i]-1];
R = mpR[nums[i]+1];
// 更新当前节点,防止下次读入,不然会WA
mpL[nums[i]] = L+1;
mpR[nums[i]] = R+1;
// 更新边界
mpL[nums[i]+R] = mpR[nums[i]-L] = R+L+1;
ans = max(ans,L+R+1);
}
return ans;
}
};
// @lc code=end