解题思路:
(1)根据map的依据key排序属性,将数组中的数字从大到小排序
(2)接下来遍历map,判断相邻key是否相差1,同时更新它们的value之和
class Solution {
public:
int findLHS(vector<int>& nums) {
if(nums.size()==0 || nums.size()==1) return 0;
map<int,int> mp;
int len = 0;
for(auto&w : nums) mp[w]++;
map<int,int>::iterator cur = mp.begin();
map<int,int>::iterator nex = next(cur);
while(nex!=mp.end()) {
if(cur->first+1==nex->first)
len = (cur->second+nex->second)>len?(cur->second+nex->second):len;
cur = nex;
nex++;
}
return len;
}
};