题目描述:
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
解法:
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<long long, int> mp;
for(int num : nums){
if(mp.find(num) == mp.end()){
mp[num] = 1;
}else{
mp[num]++;
}
}
int res = 0;
for(auto it : mp){
long long val = it.first;
if(mp.find(val+1) != mp.end()){
res = max(res, mp[val+1] + it.second);
}
}
return res;
}
};